Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot._typing import E
  25from sqlglot.errors import ParseError
  26from sqlglot.helper import (
  27    AutoName,
  28    camel_to_snake_case,
  29    ensure_collection,
  30    ensure_list,
  31    seq_get,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39
  40class _Expression(type):
  41    def __new__(cls, clsname, bases, attrs):
  42        klass = super().__new__(cls, clsname, bases, attrs)
  43
  44        # When an Expression class is created, its key is automatically set to be
  45        # the lowercase version of the class' name.
  46        klass.key = clsname.lower()
  47
  48        # This is so that docstrings are not inherited in pdoc
  49        klass.__doc__ = klass.__doc__ or ""
  50
  51        return klass
  52
  53
  54class Expression(metaclass=_Expression):
  55    """
  56    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  57    context, such as its child expressions, their names (arg keys), and whether a given child expression
  58    is optional or not.
  59
  60    Attributes:
  61        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  62            and representing expressions as strings.
  63        arg_types: determines what arguments (child nodes) are supported by an expression. It
  64            maps arg keys to booleans that indicate whether the corresponding args are optional.
  65        parent: a reference to the parent expression (or None, in case of root expressions).
  66        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  67            uses to refer to it.
  68        comments: a list of comments that are associated with a given expression. This is used in
  69            order to preserve comments when transpiling SQL code.
  70        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  71            optimizer, in order to enable some transformations that require type information.
  72
  73    Example:
  74        >>> class Foo(Expression):
  75        ...     arg_types = {"this": True, "expression": False}
  76
  77        The above definition informs us that Foo is an Expression that requires an argument called
  78        "this" and may also optionally receive an argument called "expression".
  79
  80    Args:
  81        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  82    """
  83
  84    key = "expression"
  85    arg_types = {"this": True}
  86    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  87
  88    def __init__(self, **args: t.Any):
  89        self.args: t.Dict[str, t.Any] = args
  90        self.parent: t.Optional[Expression] = None
  91        self.arg_key: t.Optional[str] = None
  92        self.comments: t.Optional[t.List[str]] = None
  93        self._type: t.Optional[DataType] = None
  94        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  95        self._hash: t.Optional[int] = None
  96
  97        for arg_key, value in self.args.items():
  98            self._set_parent(arg_key, value)
  99
 100    def __eq__(self, other) -> bool:
 101        return type(self) is type(other) and hash(self) == hash(other)
 102
 103    @property
 104    def hashable_args(self) -> t.Any:
 105        args = (self.args.get(k) for k in self.arg_types)
 106
 107        return tuple(
 108            (tuple(_norm_arg(a) for a in arg) if arg else None)
 109            if type(arg) is list
 110            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 111            for arg in args
 112        )
 113
 114    def __hash__(self) -> int:
 115        if self._hash is not None:
 116            return self._hash
 117
 118        return hash((self.__class__, self.hashable_args))
 119
 120    @property
 121    def this(self):
 122        """
 123        Retrieves the argument with key "this".
 124        """
 125        return self.args.get("this")
 126
 127    @property
 128    def expression(self):
 129        """
 130        Retrieves the argument with key "expression".
 131        """
 132        return self.args.get("expression")
 133
 134    @property
 135    def expressions(self):
 136        """
 137        Retrieves the argument with key "expressions".
 138        """
 139        return self.args.get("expressions") or []
 140
 141    def text(self, key) -> str:
 142        """
 143        Returns a textual representation of the argument corresponding to "key". This can only be used
 144        for args that are strings or leaf Expression instances, such as identifiers and literals.
 145        """
 146        field = self.args.get(key)
 147        if isinstance(field, str):
 148            return field
 149        if isinstance(field, (Identifier, Literal, Var)):
 150            return field.this
 151        if isinstance(field, (Star, Null)):
 152            return field.name
 153        return ""
 154
 155    @property
 156    def is_string(self) -> bool:
 157        """
 158        Checks whether a Literal expression is a string.
 159        """
 160        return isinstance(self, Literal) and self.args["is_string"]
 161
 162    @property
 163    def is_number(self) -> bool:
 164        """
 165        Checks whether a Literal expression is a number.
 166        """
 167        return isinstance(self, Literal) and not self.args["is_string"]
 168
 169    @property
 170    def is_int(self) -> bool:
 171        """
 172        Checks whether a Literal expression is an integer.
 173        """
 174        if self.is_number:
 175            try:
 176                int(self.name)
 177                return True
 178            except ValueError:
 179                pass
 180        return False
 181
 182    @property
 183    def is_star(self) -> bool:
 184        """Checks whether an expression is a star."""
 185        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 186
 187    @property
 188    def alias(self) -> str:
 189        """
 190        Returns the alias of the expression, or an empty string if it's not aliased.
 191        """
 192        if isinstance(self.args.get("alias"), TableAlias):
 193            return self.args["alias"].name
 194        return self.text("alias")
 195
 196    @property
 197    def name(self) -> str:
 198        return self.text("this")
 199
 200    @property
 201    def alias_or_name(self) -> str:
 202        return self.alias or self.name
 203
 204    @property
 205    def output_name(self) -> str:
 206        """
 207        Name of the output column if this expression is a selection.
 208
 209        If the Expression has no output name, an empty string is returned.
 210
 211        Example:
 212            >>> from sqlglot import parse_one
 213            >>> parse_one("SELECT a").expressions[0].output_name
 214            'a'
 215            >>> parse_one("SELECT b AS c").expressions[0].output_name
 216            'c'
 217            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 218            ''
 219        """
 220        return ""
 221
 222    @property
 223    def type(self) -> t.Optional[DataType]:
 224        return self._type
 225
 226    @type.setter
 227    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 228        if dtype and not isinstance(dtype, DataType):
 229            dtype = DataType.build(dtype)
 230        self._type = dtype  # type: ignore
 231
 232    @property
 233    def meta(self) -> t.Dict[str, t.Any]:
 234        if self._meta is None:
 235            self._meta = {}
 236        return self._meta
 237
 238    def __deepcopy__(self, memo):
 239        copy = self.__class__(**deepcopy(self.args))
 240        if self.comments is not None:
 241            copy.comments = deepcopy(self.comments)
 242
 243        if self._type is not None:
 244            copy._type = self._type.copy()
 245
 246        if self._meta is not None:
 247            copy._meta = deepcopy(self._meta)
 248
 249        return copy
 250
 251    def copy(self):
 252        """
 253        Returns a deep copy of the expression.
 254        """
 255        new = deepcopy(self)
 256        new.parent = self.parent
 257        return new
 258
 259    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
 260        if self.comments is None:
 261            self.comments = []
 262        if comments:
 263            self.comments.extend(comments)
 264
 265    def append(self, arg_key: str, value: t.Any) -> None:
 266        """
 267        Appends value to arg_key if it's a list or sets it as a new list.
 268
 269        Args:
 270            arg_key (str): name of the list expression arg
 271            value (Any): value to append to the list
 272        """
 273        if not isinstance(self.args.get(arg_key), list):
 274            self.args[arg_key] = []
 275        self.args[arg_key].append(value)
 276        self._set_parent(arg_key, value)
 277
 278    def set(self, arg_key: str, value: t.Any) -> None:
 279        """
 280        Sets `arg_key` to `value`.
 281
 282        Args:
 283            arg_key (str): name of the expression arg.
 284            value: value to set the arg to.
 285        """
 286        self.args[arg_key] = value
 287        self._set_parent(arg_key, value)
 288
 289    def _set_parent(self, arg_key: str, value: t.Any) -> None:
 290        if hasattr(value, "parent"):
 291            value.parent = self
 292            value.arg_key = arg_key
 293        elif type(value) is list:
 294            for v in value:
 295                if hasattr(v, "parent"):
 296                    v.parent = self
 297                    v.arg_key = arg_key
 298
 299    @property
 300    def depth(self) -> int:
 301        """
 302        Returns the depth of this tree.
 303        """
 304        if self.parent:
 305            return self.parent.depth + 1
 306        return 0
 307
 308    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 309        """Yields the key and expression for all arguments, exploding list args."""
 310        for k, vs in self.args.items():
 311            if type(vs) is list:
 312                for v in vs:
 313                    if hasattr(v, "parent"):
 314                        yield k, v
 315            else:
 316                if hasattr(vs, "parent"):
 317                    yield k, vs
 318
 319    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
 320        """
 321        Returns the first node in this tree which matches at least one of
 322        the specified types.
 323
 324        Args:
 325            expression_types: the expression type(s) to match.
 326            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 327
 328        Returns:
 329            The node which matches the criteria or None if no such node was found.
 330        """
 331        return next(self.find_all(*expression_types, bfs=bfs), None)
 332
 333    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
 334        """
 335        Returns a generator object which visits all nodes in this tree and only
 336        yields those that match at least one of the specified expression types.
 337
 338        Args:
 339            expression_types: the expression type(s) to match.
 340            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 341
 342        Returns:
 343            The generator object.
 344        """
 345        for expression, *_ in self.walk(bfs=bfs):
 346            if isinstance(expression, expression_types):
 347                yield expression
 348
 349    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
 350        """
 351        Returns a nearest parent matching expression_types.
 352
 353        Args:
 354            expression_types: the expression type(s) to match.
 355
 356        Returns:
 357            The parent node.
 358        """
 359        ancestor = self.parent
 360        while ancestor and not isinstance(ancestor, expression_types):
 361            ancestor = ancestor.parent
 362        return t.cast(E, ancestor)
 363
 364    @property
 365    def parent_select(self) -> t.Optional[Select]:
 366        """
 367        Returns the parent select statement.
 368        """
 369        return self.find_ancestor(Select)
 370
 371    @property
 372    def same_parent(self) -> bool:
 373        """Returns if the parent is the same class as itself."""
 374        return type(self.parent) is self.__class__
 375
 376    def root(self) -> Expression:
 377        """
 378        Returns the root expression of this tree.
 379        """
 380        expression = self
 381        while expression.parent:
 382            expression = expression.parent
 383        return expression
 384
 385    def walk(self, bfs=True, prune=None):
 386        """
 387        Returns a generator object which visits all nodes in this tree.
 388
 389        Args:
 390            bfs (bool): if set to True the BFS traversal order will be applied,
 391                otherwise the DFS traversal will be used instead.
 392            prune ((node, parent, arg_key) -> bool): callable that returns True if
 393                the generator should stop traversing this branch of the tree.
 394
 395        Returns:
 396            the generator object.
 397        """
 398        if bfs:
 399            yield from self.bfs(prune=prune)
 400        else:
 401            yield from self.dfs(prune=prune)
 402
 403    def dfs(self, parent=None, key=None, prune=None):
 404        """
 405        Returns a generator object which visits all nodes in this tree in
 406        the DFS (Depth-first) order.
 407
 408        Returns:
 409            The generator object.
 410        """
 411        parent = parent or self.parent
 412        yield self, parent, key
 413        if prune and prune(self, parent, key):
 414            return
 415
 416        for k, v in self.iter_expressions():
 417            yield from v.dfs(self, k, prune)
 418
 419    def bfs(self, prune=None):
 420        """
 421        Returns a generator object which visits all nodes in this tree in
 422        the BFS (Breadth-first) order.
 423
 424        Returns:
 425            The generator object.
 426        """
 427        queue = deque([(self, self.parent, None)])
 428
 429        while queue:
 430            item, parent, key = queue.popleft()
 431
 432            yield item, parent, key
 433            if prune and prune(item, parent, key):
 434                continue
 435
 436            for k, v in item.iter_expressions():
 437                queue.append((v, item, k))
 438
 439    def unnest(self):
 440        """
 441        Returns the first non parenthesis child or self.
 442        """
 443        expression = self
 444        while type(expression) is Paren:
 445            expression = expression.this
 446        return expression
 447
 448    def unalias(self):
 449        """
 450        Returns the inner expression if this is an Alias.
 451        """
 452        if isinstance(self, Alias):
 453            return self.this
 454        return self
 455
 456    def unnest_operands(self):
 457        """
 458        Returns unnested operands as a tuple.
 459        """
 460        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 461
 462    def flatten(self, unnest=True):
 463        """
 464        Returns a generator which yields child nodes who's parents are the same class.
 465
 466        A AND B AND C -> [A, B, C]
 467        """
 468        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 469            if not type(node) is self.__class__:
 470                yield node.unnest() if unnest else node
 471
 472    def __str__(self) -> str:
 473        return self.sql()
 474
 475    def __repr__(self) -> str:
 476        return self._to_s()
 477
 478    def sql(self, dialect: DialectType = None, **opts) -> str:
 479        """
 480        Returns SQL string representation of this tree.
 481
 482        Args:
 483            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 484            opts: other `sqlglot.generator.Generator` options.
 485
 486        Returns:
 487            The SQL string.
 488        """
 489        from sqlglot.dialects import Dialect
 490
 491        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 492
 493    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 494        indent = "" if not level else "\n"
 495        indent += "".join(["  "] * level)
 496        left = f"({self.key.upper()} "
 497
 498        args: t.Dict[str, t.Any] = {
 499            k: ", ".join(
 500                v._to_s(hide_missing=hide_missing, level=level + 1)
 501                if hasattr(v, "_to_s")
 502                else str(v)
 503                for v in ensure_list(vs)
 504                if v is not None
 505            )
 506            for k, vs in self.args.items()
 507        }
 508        args["comments"] = self.comments
 509        args["type"] = self.type
 510        args = {k: v for k, v in args.items() if v or not hide_missing}
 511
 512        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 513        right += ")"
 514
 515        return indent + left + right
 516
 517    def transform(self, fun, *args, copy=True, **kwargs):
 518        """
 519        Recursively visits all tree nodes (excluding already transformed ones)
 520        and applies the given transformation function to each node.
 521
 522        Args:
 523            fun (function): a function which takes a node as an argument and returns a
 524                new transformed node or the same node without modifications. If the function
 525                returns None, then the corresponding node will be removed from the syntax tree.
 526            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 527                modified in place.
 528
 529        Returns:
 530            The transformed tree.
 531        """
 532        node = self.copy() if copy else self
 533        new_node = fun(node, *args, **kwargs)
 534
 535        if new_node is None or not isinstance(new_node, Expression):
 536            return new_node
 537        if new_node is not node:
 538            new_node.parent = node.parent
 539            return new_node
 540
 541        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 542        return new_node
 543
 544    @t.overload
 545    def replace(self, expression: E) -> E:
 546        ...
 547
 548    @t.overload
 549    def replace(self, expression: None) -> None:
 550        ...
 551
 552    def replace(self, expression):
 553        """
 554        Swap out this expression with a new expression.
 555
 556        For example::
 557
 558            >>> tree = Select().select("x").from_("tbl")
 559            >>> tree.find(Column).replace(Column(this="y"))
 560            (COLUMN this: y)
 561            >>> tree.sql()
 562            'SELECT y FROM tbl'
 563
 564        Args:
 565            expression: new node
 566
 567        Returns:
 568            The new expression or expressions.
 569        """
 570        if not self.parent:
 571            return expression
 572
 573        parent = self.parent
 574        self.parent = None
 575
 576        replace_children(parent, lambda child: expression if child is self else child)
 577        return expression
 578
 579    def pop(self: E) -> E:
 580        """
 581        Remove this expression from its AST.
 582
 583        Returns:
 584            The popped expression.
 585        """
 586        self.replace(None)
 587        return self
 588
 589    def assert_is(self, type_: t.Type[E]) -> E:
 590        """
 591        Assert that this `Expression` is an instance of `type_`.
 592
 593        If it is NOT an instance of `type_`, this raises an assertion error.
 594        Otherwise, this returns this expression.
 595
 596        Examples:
 597            This is useful for type security in chained expressions:
 598
 599            >>> import sqlglot
 600            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 601            'SELECT x, z FROM y'
 602        """
 603        assert isinstance(self, type_)
 604        return self
 605
 606    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 607        """
 608        Checks if this expression is valid (e.g. all mandatory args are set).
 609
 610        Args:
 611            args: a sequence of values that were used to instantiate a Func expression. This is used
 612                to check that the provided arguments don't exceed the function argument limit.
 613
 614        Returns:
 615            A list of error messages for all possible errors that were found.
 616        """
 617        errors: t.List[str] = []
 618
 619        for k in self.args:
 620            if k not in self.arg_types:
 621                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 622        for k, mandatory in self.arg_types.items():
 623            v = self.args.get(k)
 624            if mandatory and (v is None or (isinstance(v, list) and not v)):
 625                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 626
 627        if (
 628            args
 629            and isinstance(self, Func)
 630            and len(args) > len(self.arg_types)
 631            and not self.is_var_len_args
 632        ):
 633            errors.append(
 634                f"The number of provided arguments ({len(args)}) is greater than "
 635                f"the maximum number of supported arguments ({len(self.arg_types)})"
 636            )
 637
 638        return errors
 639
 640    def dump(self):
 641        """
 642        Dump this Expression to a JSON-serializable dict.
 643        """
 644        from sqlglot.serde import dump
 645
 646        return dump(self)
 647
 648    @classmethod
 649    def load(cls, obj):
 650        """
 651        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 652        """
 653        from sqlglot.serde import load
 654
 655        return load(obj)
 656
 657
 658IntoType = t.Union[
 659    str,
 660    t.Type[Expression],
 661    t.Collection[t.Union[str, t.Type[Expression]]],
 662]
 663ExpOrStr = t.Union[str, Expression]
 664
 665
 666class Condition(Expression):
 667    def and_(
 668        self,
 669        *expressions: t.Optional[ExpOrStr],
 670        dialect: DialectType = None,
 671        copy: bool = True,
 672        **opts,
 673    ) -> Condition:
 674        """
 675        AND this condition with one or multiple expressions.
 676
 677        Example:
 678            >>> condition("x=1").and_("y=1").sql()
 679            'x = 1 AND y = 1'
 680
 681        Args:
 682            *expressions: the SQL code strings to parse.
 683                If an `Expression` instance is passed, it will be used as-is.
 684            dialect: the dialect used to parse the input expression.
 685            copy: whether or not to copy the involved expressions (only applies to Expressions).
 686            opts: other options to use to parse the input expressions.
 687
 688        Returns:
 689            The new And condition.
 690        """
 691        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
 692
 693    def or_(
 694        self,
 695        *expressions: t.Optional[ExpOrStr],
 696        dialect: DialectType = None,
 697        copy: bool = True,
 698        **opts,
 699    ) -> Condition:
 700        """
 701        OR this condition with one or multiple expressions.
 702
 703        Example:
 704            >>> condition("x=1").or_("y=1").sql()
 705            'x = 1 OR y = 1'
 706
 707        Args:
 708            *expressions: the SQL code strings to parse.
 709                If an `Expression` instance is passed, it will be used as-is.
 710            dialect: the dialect used to parse the input expression.
 711            copy: whether or not to copy the involved expressions (only applies to Expressions).
 712            opts: other options to use to parse the input expressions.
 713
 714        Returns:
 715            The new Or condition.
 716        """
 717        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
 718
 719    def not_(self, copy: bool = True):
 720        """
 721        Wrap this condition with NOT.
 722
 723        Example:
 724            >>> condition("x=1").not_().sql()
 725            'NOT x = 1'
 726
 727        Args:
 728            copy: whether or not to copy this object.
 729
 730        Returns:
 731            The new Not instance.
 732        """
 733        return not_(self, copy=copy)
 734
 735    def as_(
 736        self,
 737        alias: str | Identifier,
 738        quoted: t.Optional[bool] = None,
 739        dialect: DialectType = None,
 740        copy: bool = True,
 741        **opts,
 742    ) -> Alias:
 743        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
 744
 745    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
 746        this = self.copy()
 747        other = convert(other, copy=True)
 748        if not isinstance(this, klass) and not isinstance(other, klass):
 749            this = _wrap(this, Binary)
 750            other = _wrap(other, Binary)
 751        if reverse:
 752            return klass(this=other, expression=this)
 753        return klass(this=this, expression=other)
 754
 755    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
 756        return Bracket(
 757            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
 758        )
 759
 760    def isin(
 761        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
 762    ) -> In:
 763        return In(
 764            this=_maybe_copy(self, copy),
 765            expressions=[convert(e, copy=copy) for e in expressions],
 766            query=maybe_parse(query, copy=copy, **opts) if query else None,
 767        )
 768
 769    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
 770        return Between(
 771            this=_maybe_copy(self, copy),
 772            low=convert(low, copy=copy, **opts),
 773            high=convert(high, copy=copy, **opts),
 774        )
 775
 776    def is_(self, other: ExpOrStr) -> Is:
 777        return self._binop(Is, other)
 778
 779    def like(self, other: ExpOrStr) -> Like:
 780        return self._binop(Like, other)
 781
 782    def ilike(self, other: ExpOrStr) -> ILike:
 783        return self._binop(ILike, other)
 784
 785    def eq(self, other: t.Any) -> EQ:
 786        return self._binop(EQ, other)
 787
 788    def neq(self, other: t.Any) -> NEQ:
 789        return self._binop(NEQ, other)
 790
 791    def rlike(self, other: ExpOrStr) -> RegexpLike:
 792        return self._binop(RegexpLike, other)
 793
 794    def __lt__(self, other: t.Any) -> LT:
 795        return self._binop(LT, other)
 796
 797    def __le__(self, other: t.Any) -> LTE:
 798        return self._binop(LTE, other)
 799
 800    def __gt__(self, other: t.Any) -> GT:
 801        return self._binop(GT, other)
 802
 803    def __ge__(self, other: t.Any) -> GTE:
 804        return self._binop(GTE, other)
 805
 806    def __add__(self, other: t.Any) -> Add:
 807        return self._binop(Add, other)
 808
 809    def __radd__(self, other: t.Any) -> Add:
 810        return self._binop(Add, other, reverse=True)
 811
 812    def __sub__(self, other: t.Any) -> Sub:
 813        return self._binop(Sub, other)
 814
 815    def __rsub__(self, other: t.Any) -> Sub:
 816        return self._binop(Sub, other, reverse=True)
 817
 818    def __mul__(self, other: t.Any) -> Mul:
 819        return self._binop(Mul, other)
 820
 821    def __rmul__(self, other: t.Any) -> Mul:
 822        return self._binop(Mul, other, reverse=True)
 823
 824    def __truediv__(self, other: t.Any) -> Div:
 825        return self._binop(Div, other)
 826
 827    def __rtruediv__(self, other: t.Any) -> Div:
 828        return self._binop(Div, other, reverse=True)
 829
 830    def __floordiv__(self, other: t.Any) -> IntDiv:
 831        return self._binop(IntDiv, other)
 832
 833    def __rfloordiv__(self, other: t.Any) -> IntDiv:
 834        return self._binop(IntDiv, other, reverse=True)
 835
 836    def __mod__(self, other: t.Any) -> Mod:
 837        return self._binop(Mod, other)
 838
 839    def __rmod__(self, other: t.Any) -> Mod:
 840        return self._binop(Mod, other, reverse=True)
 841
 842    def __pow__(self, other: t.Any) -> Pow:
 843        return self._binop(Pow, other)
 844
 845    def __rpow__(self, other: t.Any) -> Pow:
 846        return self._binop(Pow, other, reverse=True)
 847
 848    def __and__(self, other: t.Any) -> And:
 849        return self._binop(And, other)
 850
 851    def __rand__(self, other: t.Any) -> And:
 852        return self._binop(And, other, reverse=True)
 853
 854    def __or__(self, other: t.Any) -> Or:
 855        return self._binop(Or, other)
 856
 857    def __ror__(self, other: t.Any) -> Or:
 858        return self._binop(Or, other, reverse=True)
 859
 860    def __neg__(self) -> Neg:
 861        return Neg(this=_wrap(self.copy(), Binary))
 862
 863    def __invert__(self) -> Not:
 864        return not_(self.copy())
 865
 866
 867class Predicate(Condition):
 868    """Relationships like x = y, x > 1, x >= y."""
 869
 870
 871class DerivedTable(Expression):
 872    @property
 873    def alias_column_names(self) -> t.List[str]:
 874        table_alias = self.args.get("alias")
 875        if not table_alias:
 876            return []
 877        return [c.name for c in table_alias.args.get("columns") or []]
 878
 879    @property
 880    def selects(self):
 881        return self.this.selects if isinstance(self.this, Subqueryable) else []
 882
 883    @property
 884    def named_selects(self):
 885        return [select.output_name for select in self.selects]
 886
 887
 888class Unionable(Expression):
 889    def union(
 890        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 891    ) -> Unionable:
 892        """
 893        Builds a UNION expression.
 894
 895        Example:
 896            >>> import sqlglot
 897            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 898            'SELECT * FROM foo UNION SELECT * FROM bla'
 899
 900        Args:
 901            expression: the SQL code string.
 902                If an `Expression` instance is passed, it will be used as-is.
 903            distinct: set the DISTINCT flag if and only if this is true.
 904            dialect: the dialect used to parse the input expression.
 905            opts: other options to use to parse the input expressions.
 906
 907        Returns:
 908            The new Union expression.
 909        """
 910        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 911
 912    def intersect(
 913        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 914    ) -> Unionable:
 915        """
 916        Builds an INTERSECT expression.
 917
 918        Example:
 919            >>> import sqlglot
 920            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 921            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 922
 923        Args:
 924            expression: the SQL code string.
 925                If an `Expression` instance is passed, it will be used as-is.
 926            distinct: set the DISTINCT flag if and only if this is true.
 927            dialect: the dialect used to parse the input expression.
 928            opts: other options to use to parse the input expressions.
 929
 930        Returns:
 931            The new Intersect expression.
 932        """
 933        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 934
 935    def except_(
 936        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 937    ) -> Unionable:
 938        """
 939        Builds an EXCEPT expression.
 940
 941        Example:
 942            >>> import sqlglot
 943            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 944            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 945
 946        Args:
 947            expression: the SQL code string.
 948                If an `Expression` instance is passed, it will be used as-is.
 949            distinct: set the DISTINCT flag if and only if this is true.
 950            dialect: the dialect used to parse the input expression.
 951            opts: other options to use to parse the input expressions.
 952
 953        Returns:
 954            The new Except expression.
 955        """
 956        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 957
 958
 959class UDTF(DerivedTable, Unionable):
 960    @property
 961    def selects(self):
 962        alias = self.args.get("alias")
 963        return alias.columns if alias else []
 964
 965
 966class Cache(Expression):
 967    arg_types = {
 968        "with": False,
 969        "this": True,
 970        "lazy": False,
 971        "options": False,
 972        "expression": False,
 973    }
 974
 975
 976class Uncache(Expression):
 977    arg_types = {"this": True, "exists": False}
 978
 979
 980class Create(Expression):
 981    arg_types = {
 982        "with": False,
 983        "this": True,
 984        "kind": True,
 985        "expression": False,
 986        "exists": False,
 987        "properties": False,
 988        "replace": False,
 989        "unique": False,
 990        "indexes": False,
 991        "no_schema_binding": False,
 992        "begin": False,
 993        "clone": False,
 994    }
 995
 996
 997# https://docs.snowflake.com/en/sql-reference/sql/create-clone
 998class Clone(Expression):
 999    arg_types = {
1000        "this": True,
1001        "when": False,
1002        "kind": False,
1003        "expression": False,
1004    }
1005
1006
1007class Describe(Expression):
1008    arg_types = {"this": True, "kind": False}
1009
1010
1011class Pragma(Expression):
1012    pass
1013
1014
1015class Set(Expression):
1016    arg_types = {"expressions": False, "unset": False, "tag": False}
1017
1018
1019class SetItem(Expression):
1020    arg_types = {
1021        "this": False,
1022        "expressions": False,
1023        "kind": False,
1024        "collate": False,  # MySQL SET NAMES statement
1025        "global": False,
1026    }
1027
1028
1029class Show(Expression):
1030    arg_types = {
1031        "this": True,
1032        "target": False,
1033        "offset": False,
1034        "limit": False,
1035        "like": False,
1036        "where": False,
1037        "db": False,
1038        "full": False,
1039        "mutex": False,
1040        "query": False,
1041        "channel": False,
1042        "global": False,
1043        "log": False,
1044        "position": False,
1045        "types": False,
1046    }
1047
1048
1049class UserDefinedFunction(Expression):
1050    arg_types = {"this": True, "expressions": False, "wrapped": False}
1051
1052
1053class CharacterSet(Expression):
1054    arg_types = {"this": True, "default": False}
1055
1056
1057class With(Expression):
1058    arg_types = {"expressions": True, "recursive": False}
1059
1060    @property
1061    def recursive(self) -> bool:
1062        return bool(self.args.get("recursive"))
1063
1064
1065class WithinGroup(Expression):
1066    arg_types = {"this": True, "expression": False}
1067
1068
1069class CTE(DerivedTable):
1070    arg_types = {"this": True, "alias": True}
1071
1072
1073class TableAlias(Expression):
1074    arg_types = {"this": False, "columns": False}
1075
1076    @property
1077    def columns(self):
1078        return self.args.get("columns") or []
1079
1080
1081class BitString(Condition):
1082    pass
1083
1084
1085class HexString(Condition):
1086    pass
1087
1088
1089class ByteString(Condition):
1090    pass
1091
1092
1093class RawString(Condition):
1094    pass
1095
1096
1097class Column(Condition):
1098    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1099
1100    @property
1101    def table(self) -> str:
1102        return self.text("table")
1103
1104    @property
1105    def db(self) -> str:
1106        return self.text("db")
1107
1108    @property
1109    def catalog(self) -> str:
1110        return self.text("catalog")
1111
1112    @property
1113    def output_name(self) -> str:
1114        return self.name
1115
1116    @property
1117    def parts(self) -> t.List[Identifier]:
1118        """Return the parts of a column in order catalog, db, table, name."""
1119        return [
1120            t.cast(Identifier, self.args[part])
1121            for part in ("catalog", "db", "table", "this")
1122            if self.args.get(part)
1123        ]
1124
1125    def to_dot(self) -> Dot:
1126        """Converts the column into a dot expression."""
1127        parts = self.parts
1128        parent = self.parent
1129
1130        while parent:
1131            if isinstance(parent, Dot):
1132                parts.append(parent.expression)
1133            parent = parent.parent
1134
1135        return Dot.build(parts)
1136
1137
1138class ColumnPosition(Expression):
1139    arg_types = {"this": False, "position": True}
1140
1141
1142class ColumnDef(Expression):
1143    arg_types = {
1144        "this": True,
1145        "kind": False,
1146        "constraints": False,
1147        "exists": False,
1148        "position": False,
1149    }
1150
1151    @property
1152    def constraints(self) -> t.List[ColumnConstraint]:
1153        return self.args.get("constraints") or []
1154
1155
1156class AlterColumn(Expression):
1157    arg_types = {
1158        "this": True,
1159        "dtype": False,
1160        "collate": False,
1161        "using": False,
1162        "default": False,
1163        "drop": False,
1164    }
1165
1166
1167class RenameTable(Expression):
1168    pass
1169
1170
1171class Comment(Expression):
1172    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
1173
1174
1175# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1176class MergeTreeTTLAction(Expression):
1177    arg_types = {
1178        "this": True,
1179        "delete": False,
1180        "recompress": False,
1181        "to_disk": False,
1182        "to_volume": False,
1183    }
1184
1185
1186# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1187class MergeTreeTTL(Expression):
1188    arg_types = {
1189        "expressions": True,
1190        "where": False,
1191        "group": False,
1192        "aggregates": False,
1193    }
1194
1195
1196class ColumnConstraint(Expression):
1197    arg_types = {"this": False, "kind": True}
1198
1199    @property
1200    def kind(self) -> ColumnConstraintKind:
1201        return self.args["kind"]
1202
1203
1204class ColumnConstraintKind(Expression):
1205    pass
1206
1207
1208class AutoIncrementColumnConstraint(ColumnConstraintKind):
1209    pass
1210
1211
1212class CaseSpecificColumnConstraint(ColumnConstraintKind):
1213    arg_types = {"not_": True}
1214
1215
1216class CharacterSetColumnConstraint(ColumnConstraintKind):
1217    arg_types = {"this": True}
1218
1219
1220class CheckColumnConstraint(ColumnConstraintKind):
1221    pass
1222
1223
1224class CollateColumnConstraint(ColumnConstraintKind):
1225    pass
1226
1227
1228class CommentColumnConstraint(ColumnConstraintKind):
1229    pass
1230
1231
1232class CompressColumnConstraint(ColumnConstraintKind):
1233    pass
1234
1235
1236class DateFormatColumnConstraint(ColumnConstraintKind):
1237    arg_types = {"this": True}
1238
1239
1240class DefaultColumnConstraint(ColumnConstraintKind):
1241    pass
1242
1243
1244class EncodeColumnConstraint(ColumnConstraintKind):
1245    pass
1246
1247
1248class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1249    # this: True -> ALWAYS, this: False -> BY DEFAULT
1250    arg_types = {
1251        "this": False,
1252        "expression": False,
1253        "on_null": False,
1254        "start": False,
1255        "increment": False,
1256        "minvalue": False,
1257        "maxvalue": False,
1258        "cycle": False,
1259    }
1260
1261
1262class InlineLengthColumnConstraint(ColumnConstraintKind):
1263    pass
1264
1265
1266class NotNullColumnConstraint(ColumnConstraintKind):
1267    arg_types = {"allow_null": False}
1268
1269
1270# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1271class OnUpdateColumnConstraint(ColumnConstraintKind):
1272    pass
1273
1274
1275class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1276    arg_types = {"desc": False}
1277
1278
1279class TitleColumnConstraint(ColumnConstraintKind):
1280    pass
1281
1282
1283class UniqueColumnConstraint(ColumnConstraintKind):
1284    arg_types = {"this": False}
1285
1286
1287class UppercaseColumnConstraint(ColumnConstraintKind):
1288    arg_types: t.Dict[str, t.Any] = {}
1289
1290
1291class PathColumnConstraint(ColumnConstraintKind):
1292    pass
1293
1294
1295class Constraint(Expression):
1296    arg_types = {"this": True, "expressions": True}
1297
1298
1299class Delete(Expression):
1300    arg_types = {
1301        "with": False,
1302        "this": False,
1303        "using": False,
1304        "where": False,
1305        "returning": False,
1306        "limit": False,
1307    }
1308
1309    def delete(
1310        self,
1311        table: ExpOrStr,
1312        dialect: DialectType = None,
1313        copy: bool = True,
1314        **opts,
1315    ) -> Delete:
1316        """
1317        Create a DELETE expression or replace the table on an existing DELETE expression.
1318
1319        Example:
1320            >>> delete("tbl").sql()
1321            'DELETE FROM tbl'
1322
1323        Args:
1324            table: the table from which to delete.
1325            dialect: the dialect used to parse the input expression.
1326            copy: if `False`, modify this expression instance in-place.
1327            opts: other options to use to parse the input expressions.
1328
1329        Returns:
1330            Delete: the modified expression.
1331        """
1332        return _apply_builder(
1333            expression=table,
1334            instance=self,
1335            arg="this",
1336            dialect=dialect,
1337            into=Table,
1338            copy=copy,
1339            **opts,
1340        )
1341
1342    def where(
1343        self,
1344        *expressions: t.Optional[ExpOrStr],
1345        append: bool = True,
1346        dialect: DialectType = None,
1347        copy: bool = True,
1348        **opts,
1349    ) -> Delete:
1350        """
1351        Append to or set the WHERE expressions.
1352
1353        Example:
1354            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1355            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1356
1357        Args:
1358            *expressions: the SQL code strings to parse.
1359                If an `Expression` instance is passed, it will be used as-is.
1360                Multiple expressions are combined with an AND operator.
1361            append: if `True`, AND the new expressions to any existing expression.
1362                Otherwise, this resets the expression.
1363            dialect: the dialect used to parse the input expressions.
1364            copy: if `False`, modify this expression instance in-place.
1365            opts: other options to use to parse the input expressions.
1366
1367        Returns:
1368            Delete: the modified expression.
1369        """
1370        return _apply_conjunction_builder(
1371            *expressions,
1372            instance=self,
1373            arg="where",
1374            append=append,
1375            into=Where,
1376            dialect=dialect,
1377            copy=copy,
1378            **opts,
1379        )
1380
1381    def returning(
1382        self,
1383        expression: ExpOrStr,
1384        dialect: DialectType = None,
1385        copy: bool = True,
1386        **opts,
1387    ) -> Delete:
1388        """
1389        Set the RETURNING expression. Not supported by all dialects.
1390
1391        Example:
1392            >>> delete("tbl").returning("*", dialect="postgres").sql()
1393            'DELETE FROM tbl RETURNING *'
1394
1395        Args:
1396            expression: the SQL code strings to parse.
1397                If an `Expression` instance is passed, it will be used as-is.
1398            dialect: the dialect used to parse the input expressions.
1399            copy: if `False`, modify this expression instance in-place.
1400            opts: other options to use to parse the input expressions.
1401
1402        Returns:
1403            Delete: the modified expression.
1404        """
1405        return _apply_builder(
1406            expression=expression,
1407            instance=self,
1408            arg="returning",
1409            prefix="RETURNING",
1410            dialect=dialect,
1411            copy=copy,
1412            into=Returning,
1413            **opts,
1414        )
1415
1416
1417class Drop(Expression):
1418    arg_types = {
1419        "this": False,
1420        "kind": False,
1421        "exists": False,
1422        "temporary": False,
1423        "materialized": False,
1424        "cascade": False,
1425        "constraints": False,
1426        "purge": False,
1427    }
1428
1429
1430class Filter(Expression):
1431    arg_types = {"this": True, "expression": True}
1432
1433
1434class Check(Expression):
1435    pass
1436
1437
1438class Directory(Expression):
1439    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1440    arg_types = {"this": True, "local": False, "row_format": False}
1441
1442
1443class ForeignKey(Expression):
1444    arg_types = {
1445        "expressions": True,
1446        "reference": False,
1447        "delete": False,
1448        "update": False,
1449    }
1450
1451
1452class PrimaryKey(Expression):
1453    arg_types = {"expressions": True, "options": False}
1454
1455
1456# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1457# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1458class Into(Expression):
1459    arg_types = {"this": True, "temporary": False, "unlogged": False}
1460
1461
1462class From(Expression):
1463    @property
1464    def name(self) -> str:
1465        return self.this.name
1466
1467    @property
1468    def alias_or_name(self) -> str:
1469        return self.this.alias_or_name
1470
1471
1472class Having(Expression):
1473    pass
1474
1475
1476class Hint(Expression):
1477    arg_types = {"expressions": True}
1478
1479
1480class JoinHint(Expression):
1481    arg_types = {"this": True, "expressions": True}
1482
1483
1484class Identifier(Expression):
1485    arg_types = {"this": True, "quoted": False}
1486
1487    @property
1488    def quoted(self) -> bool:
1489        return bool(self.args.get("quoted"))
1490
1491    @property
1492    def hashable_args(self) -> t.Any:
1493        if self.quoted and any(char.isupper() for char in self.this):
1494            return (self.this, self.quoted)
1495        return self.this.lower()
1496
1497    @property
1498    def output_name(self) -> str:
1499        return self.name
1500
1501
1502class Index(Expression):
1503    arg_types = {
1504        "this": False,
1505        "table": False,
1506        "using": False,
1507        "where": False,
1508        "columns": False,
1509        "unique": False,
1510        "primary": False,
1511        "amp": False,  # teradata
1512        "partition_by": False,  # teradata
1513    }
1514
1515
1516class Insert(Expression):
1517    arg_types = {
1518        "with": False,
1519        "this": True,
1520        "expression": False,
1521        "conflict": False,
1522        "returning": False,
1523        "overwrite": False,
1524        "exists": False,
1525        "partition": False,
1526        "alternative": False,
1527        "where": False,
1528    }
1529
1530    def with_(
1531        self,
1532        alias: ExpOrStr,
1533        as_: ExpOrStr,
1534        recursive: t.Optional[bool] = None,
1535        append: bool = True,
1536        dialect: DialectType = None,
1537        copy: bool = True,
1538        **opts,
1539    ) -> Insert:
1540        """
1541        Append to or set the common table expressions.
1542
1543        Example:
1544            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1545            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1546
1547        Args:
1548            alias: the SQL code string to parse as the table name.
1549                If an `Expression` instance is passed, this is used as-is.
1550            as_: the SQL code string to parse as the table expression.
1551                If an `Expression` instance is passed, it will be used as-is.
1552            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1553            append: if `True`, add to any existing expressions.
1554                Otherwise, this resets the expressions.
1555            dialect: the dialect used to parse the input expression.
1556            copy: if `False`, modify this expression instance in-place.
1557            opts: other options to use to parse the input expressions.
1558
1559        Returns:
1560            The modified expression.
1561        """
1562        return _apply_cte_builder(
1563            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1564        )
1565
1566
1567class OnConflict(Expression):
1568    arg_types = {
1569        "duplicate": False,
1570        "expressions": False,
1571        "nothing": False,
1572        "key": False,
1573        "constraint": False,
1574    }
1575
1576
1577class Returning(Expression):
1578    arg_types = {"expressions": True}
1579
1580
1581# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1582class Introducer(Expression):
1583    arg_types = {"this": True, "expression": True}
1584
1585
1586# national char, like n'utf8'
1587class National(Expression):
1588    pass
1589
1590
1591class LoadData(Expression):
1592    arg_types = {
1593        "this": True,
1594        "local": False,
1595        "overwrite": False,
1596        "inpath": True,
1597        "partition": False,
1598        "input_format": False,
1599        "serde": False,
1600    }
1601
1602
1603class Partition(Expression):
1604    arg_types = {"expressions": True}
1605
1606
1607class Fetch(Expression):
1608    arg_types = {
1609        "direction": False,
1610        "count": False,
1611        "percent": False,
1612        "with_ties": False,
1613    }
1614
1615
1616class Group(Expression):
1617    arg_types = {
1618        "expressions": False,
1619        "grouping_sets": False,
1620        "cube": False,
1621        "rollup": False,
1622        "totals": False,
1623    }
1624
1625
1626class Lambda(Expression):
1627    arg_types = {"this": True, "expressions": True}
1628
1629
1630class Limit(Expression):
1631    arg_types = {"this": False, "expression": True, "offset": False}
1632
1633
1634class Literal(Condition):
1635    arg_types = {"this": True, "is_string": True}
1636
1637    @property
1638    def hashable_args(self) -> t.Any:
1639        return (self.this, self.args.get("is_string"))
1640
1641    @classmethod
1642    def number(cls, number) -> Literal:
1643        return cls(this=str(number), is_string=False)
1644
1645    @classmethod
1646    def string(cls, string) -> Literal:
1647        return cls(this=str(string), is_string=True)
1648
1649    @property
1650    def output_name(self) -> str:
1651        return self.name
1652
1653
1654class Join(Expression):
1655    arg_types = {
1656        "this": True,
1657        "on": False,
1658        "side": False,
1659        "kind": False,
1660        "using": False,
1661        "method": False,
1662        "global": False,
1663        "hint": False,
1664    }
1665
1666    @property
1667    def method(self) -> str:
1668        return self.text("method").upper()
1669
1670    @property
1671    def kind(self) -> str:
1672        return self.text("kind").upper()
1673
1674    @property
1675    def side(self) -> str:
1676        return self.text("side").upper()
1677
1678    @property
1679    def hint(self) -> str:
1680        return self.text("hint").upper()
1681
1682    @property
1683    def alias_or_name(self) -> str:
1684        return self.this.alias_or_name
1685
1686    def on(
1687        self,
1688        *expressions: t.Optional[ExpOrStr],
1689        append: bool = True,
1690        dialect: DialectType = None,
1691        copy: bool = True,
1692        **opts,
1693    ) -> Join:
1694        """
1695        Append to or set the ON expressions.
1696
1697        Example:
1698            >>> import sqlglot
1699            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1700            'JOIN x ON y = 1'
1701
1702        Args:
1703            *expressions: the SQL code strings to parse.
1704                If an `Expression` instance is passed, it will be used as-is.
1705                Multiple expressions are combined with an AND operator.
1706            append: if `True`, AND the new expressions to any existing expression.
1707                Otherwise, this resets the expression.
1708            dialect: the dialect used to parse the input expressions.
1709            copy: if `False`, modify this expression instance in-place.
1710            opts: other options to use to parse the input expressions.
1711
1712        Returns:
1713            The modified Join expression.
1714        """
1715        join = _apply_conjunction_builder(
1716            *expressions,
1717            instance=self,
1718            arg="on",
1719            append=append,
1720            dialect=dialect,
1721            copy=copy,
1722            **opts,
1723        )
1724
1725        if join.kind == "CROSS":
1726            join.set("kind", None)
1727
1728        return join
1729
1730    def using(
1731        self,
1732        *expressions: t.Optional[ExpOrStr],
1733        append: bool = True,
1734        dialect: DialectType = None,
1735        copy: bool = True,
1736        **opts,
1737    ) -> Join:
1738        """
1739        Append to or set the USING expressions.
1740
1741        Example:
1742            >>> import sqlglot
1743            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1744            'JOIN x USING (foo, bla)'
1745
1746        Args:
1747            *expressions: the SQL code strings to parse.
1748                If an `Expression` instance is passed, it will be used as-is.
1749            append: if `True`, concatenate the new expressions to the existing "using" list.
1750                Otherwise, this resets the expression.
1751            dialect: the dialect used to parse the input expressions.
1752            copy: if `False`, modify this expression instance in-place.
1753            opts: other options to use to parse the input expressions.
1754
1755        Returns:
1756            The modified Join expression.
1757        """
1758        join = _apply_list_builder(
1759            *expressions,
1760            instance=self,
1761            arg="using",
1762            append=append,
1763            dialect=dialect,
1764            copy=copy,
1765            **opts,
1766        )
1767
1768        if join.kind == "CROSS":
1769            join.set("kind", None)
1770
1771        return join
1772
1773
1774class Lateral(UDTF):
1775    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1776
1777
1778class MatchRecognize(Expression):
1779    arg_types = {
1780        "partition_by": False,
1781        "order": False,
1782        "measures": False,
1783        "rows": False,
1784        "after": False,
1785        "pattern": False,
1786        "define": False,
1787        "alias": False,
1788    }
1789
1790
1791# Clickhouse FROM FINAL modifier
1792# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1793class Final(Expression):
1794    pass
1795
1796
1797class Offset(Expression):
1798    arg_types = {"this": False, "expression": True}
1799
1800
1801class Order(Expression):
1802    arg_types = {"this": False, "expressions": True}
1803
1804
1805# hive specific sorts
1806# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1807class Cluster(Order):
1808    pass
1809
1810
1811class Distribute(Order):
1812    pass
1813
1814
1815class Sort(Order):
1816    pass
1817
1818
1819class Ordered(Expression):
1820    arg_types = {"this": True, "desc": True, "nulls_first": True}
1821
1822
1823class Property(Expression):
1824    arg_types = {"this": True, "value": True}
1825
1826
1827class AlgorithmProperty(Property):
1828    arg_types = {"this": True}
1829
1830
1831class AutoIncrementProperty(Property):
1832    arg_types = {"this": True}
1833
1834
1835class BlockCompressionProperty(Property):
1836    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1837
1838
1839class CharacterSetProperty(Property):
1840    arg_types = {"this": True, "default": True}
1841
1842
1843class ChecksumProperty(Property):
1844    arg_types = {"on": False, "default": False}
1845
1846
1847class CollateProperty(Property):
1848    arg_types = {"this": True}
1849
1850
1851class CopyGrantsProperty(Property):
1852    arg_types = {}
1853
1854
1855class DataBlocksizeProperty(Property):
1856    arg_types = {
1857        "size": False,
1858        "units": False,
1859        "minimum": False,
1860        "maximum": False,
1861        "default": False,
1862    }
1863
1864
1865class DefinerProperty(Property):
1866    arg_types = {"this": True}
1867
1868
1869class DistKeyProperty(Property):
1870    arg_types = {"this": True}
1871
1872
1873class DistStyleProperty(Property):
1874    arg_types = {"this": True}
1875
1876
1877class EngineProperty(Property):
1878    arg_types = {"this": True}
1879
1880
1881class ToTableProperty(Property):
1882    arg_types = {"this": True}
1883
1884
1885class ExecuteAsProperty(Property):
1886    arg_types = {"this": True}
1887
1888
1889class ExternalProperty(Property):
1890    arg_types = {"this": False}
1891
1892
1893class FallbackProperty(Property):
1894    arg_types = {"no": True, "protection": False}
1895
1896
1897class FileFormatProperty(Property):
1898    arg_types = {"this": True}
1899
1900
1901class FreespaceProperty(Property):
1902    arg_types = {"this": True, "percent": False}
1903
1904
1905class InputOutputFormat(Expression):
1906    arg_types = {"input_format": False, "output_format": False}
1907
1908
1909class IsolatedLoadingProperty(Property):
1910    arg_types = {
1911        "no": True,
1912        "concurrent": True,
1913        "for_all": True,
1914        "for_insert": True,
1915        "for_none": True,
1916    }
1917
1918
1919class JournalProperty(Property):
1920    arg_types = {
1921        "no": False,
1922        "dual": False,
1923        "before": False,
1924        "local": False,
1925        "after": False,
1926    }
1927
1928
1929class LanguageProperty(Property):
1930    arg_types = {"this": True}
1931
1932
1933class DictProperty(Property):
1934    arg_types = {"this": True, "kind": True, "settings": False}
1935
1936
1937class DictSubProperty(Property):
1938    pass
1939
1940
1941class DictRange(Property):
1942    arg_types = {"this": True, "min": True, "max": True}
1943
1944
1945# Clickhouse CREATE ... ON CLUSTER modifier
1946# https://clickhouse.com/docs/en/sql-reference/distributed-ddl
1947class OnCluster(Property):
1948    arg_types = {"this": True}
1949
1950
1951class LikeProperty(Property):
1952    arg_types = {"this": True, "expressions": False}
1953
1954
1955class LocationProperty(Property):
1956    arg_types = {"this": True}
1957
1958
1959class LockingProperty(Property):
1960    arg_types = {
1961        "this": False,
1962        "kind": True,
1963        "for_or_in": True,
1964        "lock_type": True,
1965        "override": False,
1966    }
1967
1968
1969class LogProperty(Property):
1970    arg_types = {"no": True}
1971
1972
1973class MaterializedProperty(Property):
1974    arg_types = {"this": False}
1975
1976
1977class MergeBlockRatioProperty(Property):
1978    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1979
1980
1981class NoPrimaryIndexProperty(Property):
1982    arg_types = {}
1983
1984
1985class OnCommitProperty(Property):
1986    arg_type = {"delete": False}
1987
1988
1989class PartitionedByProperty(Property):
1990    arg_types = {"this": True}
1991
1992
1993class ReturnsProperty(Property):
1994    arg_types = {"this": True, "is_table": False, "table": False}
1995
1996
1997class RowFormatProperty(Property):
1998    arg_types = {"this": True}
1999
2000
2001class RowFormatDelimitedProperty(Property):
2002    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2003    arg_types = {
2004        "fields": False,
2005        "escaped": False,
2006        "collection_items": False,
2007        "map_keys": False,
2008        "lines": False,
2009        "null": False,
2010        "serde": False,
2011    }
2012
2013
2014class RowFormatSerdeProperty(Property):
2015    arg_types = {"this": True}
2016
2017
2018class SchemaCommentProperty(Property):
2019    arg_types = {"this": True}
2020
2021
2022class SerdeProperties(Property):
2023    arg_types = {"expressions": True}
2024
2025
2026class SetProperty(Property):
2027    arg_types = {"multi": True}
2028
2029
2030class SettingsProperty(Property):
2031    arg_types = {"expressions": True}
2032
2033
2034class SortKeyProperty(Property):
2035    arg_types = {"this": True, "compound": False}
2036
2037
2038class SqlSecurityProperty(Property):
2039    arg_types = {"definer": True}
2040
2041
2042class StabilityProperty(Property):
2043    arg_types = {"this": True}
2044
2045
2046class TemporaryProperty(Property):
2047    arg_types = {}
2048
2049
2050class TransientProperty(Property):
2051    arg_types = {"this": False}
2052
2053
2054class VolatileProperty(Property):
2055    arg_types = {"this": False}
2056
2057
2058class WithDataProperty(Property):
2059    arg_types = {"no": True, "statistics": False}
2060
2061
2062class WithJournalTableProperty(Property):
2063    arg_types = {"this": True}
2064
2065
2066class Properties(Expression):
2067    arg_types = {"expressions": True}
2068
2069    NAME_TO_PROPERTY = {
2070        "ALGORITHM": AlgorithmProperty,
2071        "AUTO_INCREMENT": AutoIncrementProperty,
2072        "CHARACTER SET": CharacterSetProperty,
2073        "COLLATE": CollateProperty,
2074        "COMMENT": SchemaCommentProperty,
2075        "DEFINER": DefinerProperty,
2076        "DISTKEY": DistKeyProperty,
2077        "DISTSTYLE": DistStyleProperty,
2078        "ENGINE": EngineProperty,
2079        "EXECUTE AS": ExecuteAsProperty,
2080        "FORMAT": FileFormatProperty,
2081        "LANGUAGE": LanguageProperty,
2082        "LOCATION": LocationProperty,
2083        "PARTITIONED_BY": PartitionedByProperty,
2084        "RETURNS": ReturnsProperty,
2085        "ROW_FORMAT": RowFormatProperty,
2086        "SORTKEY": SortKeyProperty,
2087    }
2088
2089    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2090
2091    # CREATE property locations
2092    # Form: schema specified
2093    #   create [POST_CREATE]
2094    #     table a [POST_NAME]
2095    #     (b int) [POST_SCHEMA]
2096    #     with ([POST_WITH])
2097    #     index (b) [POST_INDEX]
2098    #
2099    # Form: alias selection
2100    #   create [POST_CREATE]
2101    #     table a [POST_NAME]
2102    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2103    #     index (c) [POST_INDEX]
2104    class Location(AutoName):
2105        POST_CREATE = auto()
2106        POST_NAME = auto()
2107        POST_SCHEMA = auto()
2108        POST_WITH = auto()
2109        POST_ALIAS = auto()
2110        POST_EXPRESSION = auto()
2111        POST_INDEX = auto()
2112        UNSUPPORTED = auto()
2113
2114    @classmethod
2115    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2116        expressions = []
2117        for key, value in properties_dict.items():
2118            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2119            if property_cls:
2120                expressions.append(property_cls(this=convert(value)))
2121            else:
2122                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2123
2124        return cls(expressions=expressions)
2125
2126
2127class Qualify(Expression):
2128    pass
2129
2130
2131# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
2132class Return(Expression):
2133    pass
2134
2135
2136class Reference(Expression):
2137    arg_types = {"this": True, "expressions": False, "options": False}
2138
2139
2140class Tuple(Expression):
2141    arg_types = {"expressions": False}
2142
2143    def isin(
2144        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2145    ) -> In:
2146        return In(
2147            this=_maybe_copy(self, copy),
2148            expressions=[convert(e, copy=copy) for e in expressions],
2149            query=maybe_parse(query, copy=copy, **opts) if query else None,
2150        )
2151
2152
2153class Subqueryable(Unionable):
2154    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2155        """
2156        Convert this expression to an aliased expression that can be used as a Subquery.
2157
2158        Example:
2159            >>> subquery = Select().select("x").from_("tbl").subquery()
2160            >>> Select().select("x").from_(subquery).sql()
2161            'SELECT x FROM (SELECT x FROM tbl)'
2162
2163        Args:
2164            alias (str | Identifier): an optional alias for the subquery
2165            copy (bool): if `False`, modify this expression instance in-place.
2166
2167        Returns:
2168            Alias: the subquery
2169        """
2170        instance = _maybe_copy(self, copy)
2171        if not isinstance(alias, Expression):
2172            alias = TableAlias(this=to_identifier(alias)) if alias else None
2173
2174        return Subquery(this=instance, alias=alias)
2175
2176    def limit(
2177        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2178    ) -> Select:
2179        raise NotImplementedError
2180
2181    @property
2182    def ctes(self):
2183        with_ = self.args.get("with")
2184        if not with_:
2185            return []
2186        return with_.expressions
2187
2188    @property
2189    def selects(self):
2190        raise NotImplementedError("Subqueryable objects must implement `selects`")
2191
2192    @property
2193    def named_selects(self):
2194        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2195
2196    def with_(
2197        self,
2198        alias: ExpOrStr,
2199        as_: ExpOrStr,
2200        recursive: t.Optional[bool] = None,
2201        append: bool = True,
2202        dialect: DialectType = None,
2203        copy: bool = True,
2204        **opts,
2205    ) -> Subqueryable:
2206        """
2207        Append to or set the common table expressions.
2208
2209        Example:
2210            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2211            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2212
2213        Args:
2214            alias: the SQL code string to parse as the table name.
2215                If an `Expression` instance is passed, this is used as-is.
2216            as_: the SQL code string to parse as the table expression.
2217                If an `Expression` instance is passed, it will be used as-is.
2218            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2219            append: if `True`, add to any existing expressions.
2220                Otherwise, this resets the expressions.
2221            dialect: the dialect used to parse the input expression.
2222            copy: if `False`, modify this expression instance in-place.
2223            opts: other options to use to parse the input expressions.
2224
2225        Returns:
2226            The modified expression.
2227        """
2228        return _apply_cte_builder(
2229            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2230        )
2231
2232
2233QUERY_MODIFIERS = {
2234    "match": False,
2235    "laterals": False,
2236    "joins": False,
2237    "pivots": False,
2238    "where": False,
2239    "group": False,
2240    "having": False,
2241    "qualify": False,
2242    "windows": False,
2243    "distribute": False,
2244    "sort": False,
2245    "cluster": False,
2246    "order": False,
2247    "limit": False,
2248    "offset": False,
2249    "locks": False,
2250    "sample": False,
2251    "settings": False,
2252    "format": False,
2253}
2254
2255
2256# https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-ver16
2257class WithTableHint(Expression):
2258    arg_types = {"expressions": True}
2259
2260
2261# https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
2262class IndexTableHint(Expression):
2263    arg_types = {"this": True, "expressions": False, "target": False}
2264
2265
2266class Table(Expression):
2267    arg_types = {
2268        "this": True,
2269        "alias": False,
2270        "db": False,
2271        "catalog": False,
2272        "laterals": False,
2273        "joins": False,
2274        "pivots": False,
2275        "hints": False,
2276        "system_time": False,
2277    }
2278
2279    @property
2280    def db(self) -> str:
2281        return self.text("db")
2282
2283    @property
2284    def catalog(self) -> str:
2285        return self.text("catalog")
2286
2287    @property
2288    def parts(self) -> t.List[Identifier]:
2289        """Return the parts of a table in order catalog, db, table."""
2290        return [
2291            t.cast(Identifier, self.args[part])
2292            for part in ("catalog", "db", "this")
2293            if self.args.get(part)
2294        ]
2295
2296
2297# See the TSQL "Querying data in a system-versioned temporal table" page
2298class SystemTime(Expression):
2299    arg_types = {
2300        "this": False,
2301        "expression": False,
2302        "kind": True,
2303    }
2304
2305
2306class Union(Subqueryable):
2307    arg_types = {
2308        "with": False,
2309        "this": True,
2310        "expression": True,
2311        "distinct": False,
2312        **QUERY_MODIFIERS,
2313    }
2314
2315    def limit(
2316        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2317    ) -> Select:
2318        """
2319        Set the LIMIT expression.
2320
2321        Example:
2322            >>> select("1").union(select("1")).limit(1).sql()
2323            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2324
2325        Args:
2326            expression: the SQL code string to parse.
2327                This can also be an integer.
2328                If a `Limit` instance is passed, this is used as-is.
2329                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2330            dialect: the dialect used to parse the input expression.
2331            copy: if `False`, modify this expression instance in-place.
2332            opts: other options to use to parse the input expressions.
2333
2334        Returns:
2335            The limited subqueryable.
2336        """
2337        return (
2338            select("*")
2339            .from_(self.subquery(alias="_l_0", copy=copy))
2340            .limit(expression, dialect=dialect, copy=False, **opts)
2341        )
2342
2343    def select(
2344        self,
2345        *expressions: t.Optional[ExpOrStr],
2346        append: bool = True,
2347        dialect: DialectType = None,
2348        copy: bool = True,
2349        **opts,
2350    ) -> Union:
2351        """Append to or set the SELECT of the union recursively.
2352
2353        Example:
2354            >>> from sqlglot import parse_one
2355            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2356            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2357
2358        Args:
2359            *expressions: the SQL code strings to parse.
2360                If an `Expression` instance is passed, it will be used as-is.
2361            append: if `True`, add to any existing expressions.
2362                Otherwise, this resets the expressions.
2363            dialect: the dialect used to parse the input expressions.
2364            copy: if `False`, modify this expression instance in-place.
2365            opts: other options to use to parse the input expressions.
2366
2367        Returns:
2368            Union: the modified expression.
2369        """
2370        this = self.copy() if copy else self
2371        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2372        this.expression.unnest().select(
2373            *expressions, append=append, dialect=dialect, copy=False, **opts
2374        )
2375        return this
2376
2377    @property
2378    def named_selects(self):
2379        return self.this.unnest().named_selects
2380
2381    @property
2382    def is_star(self) -> bool:
2383        return self.this.is_star or self.expression.is_star
2384
2385    @property
2386    def selects(self):
2387        return self.this.unnest().selects
2388
2389    @property
2390    def left(self):
2391        return self.this
2392
2393    @property
2394    def right(self):
2395        return self.expression
2396
2397
2398class Except(Union):
2399    pass
2400
2401
2402class Intersect(Union):
2403    pass
2404
2405
2406class Unnest(UDTF):
2407    arg_types = {
2408        "expressions": True,
2409        "ordinality": False,
2410        "alias": False,
2411        "offset": False,
2412    }
2413
2414
2415class Update(Expression):
2416    arg_types = {
2417        "with": False,
2418        "this": False,
2419        "expressions": True,
2420        "from": False,
2421        "where": False,
2422        "returning": False,
2423        "limit": False,
2424    }
2425
2426
2427class Values(UDTF):
2428    arg_types = {
2429        "expressions": True,
2430        "ordinality": False,
2431        "alias": False,
2432    }
2433
2434
2435class Var(Expression):
2436    pass
2437
2438
2439class Schema(Expression):
2440    arg_types = {"this": False, "expressions": False}
2441
2442
2443# https://dev.mysql.com/doc/refman/8.0/en/select.html
2444# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html
2445class Lock(Expression):
2446    arg_types = {"update": True, "expressions": False, "wait": False}
2447
2448
2449class Select(Subqueryable):
2450    arg_types = {
2451        "with": False,
2452        "kind": False,
2453        "expressions": False,
2454        "hint": False,
2455        "distinct": False,
2456        "into": False,
2457        "from": False,
2458        **QUERY_MODIFIERS,
2459    }
2460
2461    def from_(
2462        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2463    ) -> Select:
2464        """
2465        Set the FROM expression.
2466
2467        Example:
2468            >>> Select().from_("tbl").select("x").sql()
2469            'SELECT x FROM tbl'
2470
2471        Args:
2472            expression : the SQL code strings to parse.
2473                If a `From` instance is passed, this is used as-is.
2474                If another `Expression` instance is passed, it will be wrapped in a `From`.
2475            dialect: the dialect used to parse the input expression.
2476            copy: if `False`, modify this expression instance in-place.
2477            opts: other options to use to parse the input expressions.
2478
2479        Returns:
2480            The modified Select expression.
2481        """
2482        return _apply_builder(
2483            expression=expression,
2484            instance=self,
2485            arg="from",
2486            into=From,
2487            prefix="FROM",
2488            dialect=dialect,
2489            copy=copy,
2490            **opts,
2491        )
2492
2493    def group_by(
2494        self,
2495        *expressions: t.Optional[ExpOrStr],
2496        append: bool = True,
2497        dialect: DialectType = None,
2498        copy: bool = True,
2499        **opts,
2500    ) -> Select:
2501        """
2502        Set the GROUP BY expression.
2503
2504        Example:
2505            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2506            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2507
2508        Args:
2509            *expressions: the SQL code strings to parse.
2510                If a `Group` instance is passed, this is used as-is.
2511                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2512                If nothing is passed in then a group by is not applied to the expression
2513            append: if `True`, add to any existing expressions.
2514                Otherwise, this flattens all the `Group` expression into a single expression.
2515            dialect: the dialect used to parse the input expression.
2516            copy: if `False`, modify this expression instance in-place.
2517            opts: other options to use to parse the input expressions.
2518
2519        Returns:
2520            The modified Select expression.
2521        """
2522        if not expressions:
2523            return self if not copy else self.copy()
2524
2525        return _apply_child_list_builder(
2526            *expressions,
2527            instance=self,
2528            arg="group",
2529            append=append,
2530            copy=copy,
2531            prefix="GROUP BY",
2532            into=Group,
2533            dialect=dialect,
2534            **opts,
2535        )
2536
2537    def order_by(
2538        self,
2539        *expressions: t.Optional[ExpOrStr],
2540        append: bool = True,
2541        dialect: DialectType = None,
2542        copy: bool = True,
2543        **opts,
2544    ) -> Select:
2545        """
2546        Set the ORDER BY expression.
2547
2548        Example:
2549            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2550            'SELECT x FROM tbl ORDER BY x DESC'
2551
2552        Args:
2553            *expressions: the SQL code strings to parse.
2554                If a `Group` instance is passed, this is used as-is.
2555                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2556            append: if `True`, add to any existing expressions.
2557                Otherwise, this flattens all the `Order` expression into a single expression.
2558            dialect: the dialect used to parse the input expression.
2559            copy: if `False`, modify this expression instance in-place.
2560            opts: other options to use to parse the input expressions.
2561
2562        Returns:
2563            The modified Select expression.
2564        """
2565        return _apply_child_list_builder(
2566            *expressions,
2567            instance=self,
2568            arg="order",
2569            append=append,
2570            copy=copy,
2571            prefix="ORDER BY",
2572            into=Order,
2573            dialect=dialect,
2574            **opts,
2575        )
2576
2577    def sort_by(
2578        self,
2579        *expressions: t.Optional[ExpOrStr],
2580        append: bool = True,
2581        dialect: DialectType = None,
2582        copy: bool = True,
2583        **opts,
2584    ) -> Select:
2585        """
2586        Set the SORT BY expression.
2587
2588        Example:
2589            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2590            'SELECT x FROM tbl SORT BY x DESC'
2591
2592        Args:
2593            *expressions: the SQL code strings to parse.
2594                If a `Group` instance is passed, this is used as-is.
2595                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2596            append: if `True`, add to any existing expressions.
2597                Otherwise, this flattens all the `Order` expression into a single expression.
2598            dialect: the dialect used to parse the input expression.
2599            copy: if `False`, modify this expression instance in-place.
2600            opts: other options to use to parse the input expressions.
2601
2602        Returns:
2603            The modified Select expression.
2604        """
2605        return _apply_child_list_builder(
2606            *expressions,
2607            instance=self,
2608            arg="sort",
2609            append=append,
2610            copy=copy,
2611            prefix="SORT BY",
2612            into=Sort,
2613            dialect=dialect,
2614            **opts,
2615        )
2616
2617    def cluster_by(
2618        self,
2619        *expressions: t.Optional[ExpOrStr],
2620        append: bool = True,
2621        dialect: DialectType = None,
2622        copy: bool = True,
2623        **opts,
2624    ) -> Select:
2625        """
2626        Set the CLUSTER BY expression.
2627
2628        Example:
2629            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2630            'SELECT x FROM tbl CLUSTER BY x DESC'
2631
2632        Args:
2633            *expressions: the SQL code strings to parse.
2634                If a `Group` instance is passed, this is used as-is.
2635                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2636            append: if `True`, add to any existing expressions.
2637                Otherwise, this flattens all the `Order` expression into a single expression.
2638            dialect: the dialect used to parse the input expression.
2639            copy: if `False`, modify this expression instance in-place.
2640            opts: other options to use to parse the input expressions.
2641
2642        Returns:
2643            The modified Select expression.
2644        """
2645        return _apply_child_list_builder(
2646            *expressions,
2647            instance=self,
2648            arg="cluster",
2649            append=append,
2650            copy=copy,
2651            prefix="CLUSTER BY",
2652            into=Cluster,
2653            dialect=dialect,
2654            **opts,
2655        )
2656
2657    def limit(
2658        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2659    ) -> Select:
2660        """
2661        Set the LIMIT expression.
2662
2663        Example:
2664            >>> Select().from_("tbl").select("x").limit(10).sql()
2665            'SELECT x FROM tbl LIMIT 10'
2666
2667        Args:
2668            expression: the SQL code string to parse.
2669                This can also be an integer.
2670                If a `Limit` instance is passed, this is used as-is.
2671                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2672            dialect: the dialect used to parse the input expression.
2673            copy: if `False`, modify this expression instance in-place.
2674            opts: other options to use to parse the input expressions.
2675
2676        Returns:
2677            Select: the modified expression.
2678        """
2679        return _apply_builder(
2680            expression=expression,
2681            instance=self,
2682            arg="limit",
2683            into=Limit,
2684            prefix="LIMIT",
2685            dialect=dialect,
2686            copy=copy,
2687            **opts,
2688        )
2689
2690    def offset(
2691        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2692    ) -> Select:
2693        """
2694        Set the OFFSET expression.
2695
2696        Example:
2697            >>> Select().from_("tbl").select("x").offset(10).sql()
2698            'SELECT x FROM tbl OFFSET 10'
2699
2700        Args:
2701            expression: the SQL code string to parse.
2702                This can also be an integer.
2703                If a `Offset` instance is passed, this is used as-is.
2704                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2705            dialect: the dialect used to parse the input expression.
2706            copy: if `False`, modify this expression instance in-place.
2707            opts: other options to use to parse the input expressions.
2708
2709        Returns:
2710            The modified Select expression.
2711        """
2712        return _apply_builder(
2713            expression=expression,
2714            instance=self,
2715            arg="offset",
2716            into=Offset,
2717            prefix="OFFSET",
2718            dialect=dialect,
2719            copy=copy,
2720            **opts,
2721        )
2722
2723    def select(
2724        self,
2725        *expressions: t.Optional[ExpOrStr],
2726        append: bool = True,
2727        dialect: DialectType = None,
2728        copy: bool = True,
2729        **opts,
2730    ) -> Select:
2731        """
2732        Append to or set the SELECT expressions.
2733
2734        Example:
2735            >>> Select().select("x", "y").sql()
2736            'SELECT x, y'
2737
2738        Args:
2739            *expressions: the SQL code strings to parse.
2740                If an `Expression` instance is passed, it will be used as-is.
2741            append: if `True`, add to any existing expressions.
2742                Otherwise, this resets the expressions.
2743            dialect: the dialect used to parse the input expressions.
2744            copy: if `False`, modify this expression instance in-place.
2745            opts: other options to use to parse the input expressions.
2746
2747        Returns:
2748            The modified Select expression.
2749        """
2750        return _apply_list_builder(
2751            *expressions,
2752            instance=self,
2753            arg="expressions",
2754            append=append,
2755            dialect=dialect,
2756            copy=copy,
2757            **opts,
2758        )
2759
2760    def lateral(
2761        self,
2762        *expressions: t.Optional[ExpOrStr],
2763        append: bool = True,
2764        dialect: DialectType = None,
2765        copy: bool = True,
2766        **opts,
2767    ) -> Select:
2768        """
2769        Append to or set the LATERAL expressions.
2770
2771        Example:
2772            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2773            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2774
2775        Args:
2776            *expressions: the SQL code strings to parse.
2777                If an `Expression` instance is passed, it will be used as-is.
2778            append: if `True`, add to any existing expressions.
2779                Otherwise, this resets the expressions.
2780            dialect: the dialect used to parse the input expressions.
2781            copy: if `False`, modify this expression instance in-place.
2782            opts: other options to use to parse the input expressions.
2783
2784        Returns:
2785            The modified Select expression.
2786        """
2787        return _apply_list_builder(
2788            *expressions,
2789            instance=self,
2790            arg="laterals",
2791            append=append,
2792            into=Lateral,
2793            prefix="LATERAL VIEW",
2794            dialect=dialect,
2795            copy=copy,
2796            **opts,
2797        )
2798
2799    def join(
2800        self,
2801        expression: ExpOrStr,
2802        on: t.Optional[ExpOrStr] = None,
2803        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2804        append: bool = True,
2805        join_type: t.Optional[str] = None,
2806        join_alias: t.Optional[Identifier | str] = None,
2807        dialect: DialectType = None,
2808        copy: bool = True,
2809        **opts,
2810    ) -> Select:
2811        """
2812        Append to or set the JOIN expressions.
2813
2814        Example:
2815            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2816            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2817
2818            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2819            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2820
2821            Use `join_type` to change the type of join:
2822
2823            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2824            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2825
2826        Args:
2827            expression: the SQL code string to parse.
2828                If an `Expression` instance is passed, it will be used as-is.
2829            on: optionally specify the join "on" criteria as a SQL string.
2830                If an `Expression` instance is passed, it will be used as-is.
2831            using: optionally specify the join "using" criteria as a SQL string.
2832                If an `Expression` instance is passed, it will be used as-is.
2833            append: if `True`, add to any existing expressions.
2834                Otherwise, this resets the expressions.
2835            join_type: if set, alter the parsed join type.
2836            join_alias: an optional alias for the joined source.
2837            dialect: the dialect used to parse the input expressions.
2838            copy: if `False`, modify this expression instance in-place.
2839            opts: other options to use to parse the input expressions.
2840
2841        Returns:
2842            Select: the modified expression.
2843        """
2844        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2845
2846        try:
2847            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2848        except ParseError:
2849            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2850
2851        join = expression if isinstance(expression, Join) else Join(this=expression)
2852
2853        if isinstance(join.this, Select):
2854            join.this.replace(join.this.subquery())
2855
2856        if join_type:
2857            method: t.Optional[Token]
2858            side: t.Optional[Token]
2859            kind: t.Optional[Token]
2860
2861            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2862
2863            if method:
2864                join.set("method", method.text)
2865            if side:
2866                join.set("side", side.text)
2867            if kind:
2868                join.set("kind", kind.text)
2869
2870        if on:
2871            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2872            join.set("on", on)
2873
2874        if using:
2875            join = _apply_list_builder(
2876                *ensure_list(using),
2877                instance=join,
2878                arg="using",
2879                append=append,
2880                copy=copy,
2881                **opts,
2882            )
2883
2884        if join_alias:
2885            join.set("this", alias_(join.this, join_alias, table=True))
2886
2887        return _apply_list_builder(
2888            join,
2889            instance=self,
2890            arg="joins",
2891            append=append,
2892            copy=copy,
2893            **opts,
2894        )
2895
2896    def where(
2897        self,
2898        *expressions: t.Optional[ExpOrStr],
2899        append: bool = True,
2900        dialect: DialectType = None,
2901        copy: bool = True,
2902        **opts,
2903    ) -> Select:
2904        """
2905        Append to or set the WHERE expressions.
2906
2907        Example:
2908            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2909            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2910
2911        Args:
2912            *expressions: the SQL code strings to parse.
2913                If an `Expression` instance is passed, it will be used as-is.
2914                Multiple expressions are combined with an AND operator.
2915            append: if `True`, AND the new expressions to any existing expression.
2916                Otherwise, this resets the expression.
2917            dialect: the dialect used to parse the input expressions.
2918            copy: if `False`, modify this expression instance in-place.
2919            opts: other options to use to parse the input expressions.
2920
2921        Returns:
2922            Select: the modified expression.
2923        """
2924        return _apply_conjunction_builder(
2925            *expressions,
2926            instance=self,
2927            arg="where",
2928            append=append,
2929            into=Where,
2930            dialect=dialect,
2931            copy=copy,
2932            **opts,
2933        )
2934
2935    def having(
2936        self,
2937        *expressions: t.Optional[ExpOrStr],
2938        append: bool = True,
2939        dialect: DialectType = None,
2940        copy: bool = True,
2941        **opts,
2942    ) -> Select:
2943        """
2944        Append to or set the HAVING expressions.
2945
2946        Example:
2947            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2948            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2949
2950        Args:
2951            *expressions: the SQL code strings to parse.
2952                If an `Expression` instance is passed, it will be used as-is.
2953                Multiple expressions are combined with an AND operator.
2954            append: if `True`, AND the new expressions to any existing expression.
2955                Otherwise, this resets the expression.
2956            dialect: the dialect used to parse the input expressions.
2957            copy: if `False`, modify this expression instance in-place.
2958            opts: other options to use to parse the input expressions.
2959
2960        Returns:
2961            The modified Select expression.
2962        """
2963        return _apply_conjunction_builder(
2964            *expressions,
2965            instance=self,
2966            arg="having",
2967            append=append,
2968            into=Having,
2969            dialect=dialect,
2970            copy=copy,
2971            **opts,
2972        )
2973
2974    def window(
2975        self,
2976        *expressions: t.Optional[ExpOrStr],
2977        append: bool = True,
2978        dialect: DialectType = None,
2979        copy: bool = True,
2980        **opts,
2981    ) -> Select:
2982        return _apply_list_builder(
2983            *expressions,
2984            instance=self,
2985            arg="windows",
2986            append=append,
2987            into=Window,
2988            dialect=dialect,
2989            copy=copy,
2990            **opts,
2991        )
2992
2993    def qualify(
2994        self,
2995        *expressions: t.Optional[ExpOrStr],
2996        append: bool = True,
2997        dialect: DialectType = None,
2998        copy: bool = True,
2999        **opts,
3000    ) -> Select:
3001        return _apply_conjunction_builder(
3002            *expressions,
3003            instance=self,
3004            arg="qualify",
3005            append=append,
3006            into=Qualify,
3007            dialect=dialect,
3008            copy=copy,
3009            **opts,
3010        )
3011
3012    def distinct(
3013        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3014    ) -> Select:
3015        """
3016        Set the OFFSET expression.
3017
3018        Example:
3019            >>> Select().from_("tbl").select("x").distinct().sql()
3020            'SELECT DISTINCT x FROM tbl'
3021
3022        Args:
3023            ons: the expressions to distinct on
3024            distinct: whether the Select should be distinct
3025            copy: if `False`, modify this expression instance in-place.
3026
3027        Returns:
3028            Select: the modified expression.
3029        """
3030        instance = _maybe_copy(self, copy)
3031        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3032        instance.set("distinct", Distinct(on=on) if distinct else None)
3033        return instance
3034
3035    def ctas(
3036        self,
3037        table: ExpOrStr,
3038        properties: t.Optional[t.Dict] = None,
3039        dialect: DialectType = None,
3040        copy: bool = True,
3041        **opts,
3042    ) -> Create:
3043        """
3044        Convert this expression to a CREATE TABLE AS statement.
3045
3046        Example:
3047            >>> Select().select("*").from_("tbl").ctas("x").sql()
3048            'CREATE TABLE x AS SELECT * FROM tbl'
3049
3050        Args:
3051            table: the SQL code string to parse as the table name.
3052                If another `Expression` instance is passed, it will be used as-is.
3053            properties: an optional mapping of table properties
3054            dialect: the dialect used to parse the input table.
3055            copy: if `False`, modify this expression instance in-place.
3056            opts: other options to use to parse the input table.
3057
3058        Returns:
3059            The new Create expression.
3060        """
3061        instance = _maybe_copy(self, copy)
3062        table_expression = maybe_parse(
3063            table,
3064            into=Table,
3065            dialect=dialect,
3066            **opts,
3067        )
3068        properties_expression = None
3069        if properties:
3070            properties_expression = Properties.from_dict(properties)
3071
3072        return Create(
3073            this=table_expression,
3074            kind="table",
3075            expression=instance,
3076            properties=properties_expression,
3077        )
3078
3079    def lock(self, update: bool = True, copy: bool = True) -> Select:
3080        """
3081        Set the locking read mode for this expression.
3082
3083        Examples:
3084            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3085            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3086
3087            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3088            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3089
3090        Args:
3091            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3092            copy: if `False`, modify this expression instance in-place.
3093
3094        Returns:
3095            The modified expression.
3096        """
3097        inst = _maybe_copy(self, copy)
3098        inst.set("locks", [Lock(update=update)])
3099
3100        return inst
3101
3102    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3103        """
3104        Set hints for this expression.
3105
3106        Examples:
3107            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3108            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3109
3110        Args:
3111            hints: The SQL code strings to parse as the hints.
3112                If an `Expression` instance is passed, it will be used as-is.
3113            dialect: The dialect used to parse the hints.
3114            copy: If `False`, modify this expression instance in-place.
3115
3116        Returns:
3117            The modified expression.
3118        """
3119        inst = _maybe_copy(self, copy)
3120        inst.set(
3121            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3122        )
3123
3124        return inst
3125
3126    @property
3127    def named_selects(self) -> t.List[str]:
3128        return [e.output_name for e in self.expressions if e.alias_or_name]
3129
3130    @property
3131    def is_star(self) -> bool:
3132        return any(expression.is_star for expression in self.expressions)
3133
3134    @property
3135    def selects(self) -> t.List[Expression]:
3136        return self.expressions
3137
3138
3139class Subquery(DerivedTable, Unionable):
3140    arg_types = {
3141        "this": True,
3142        "alias": False,
3143        "with": False,
3144        **QUERY_MODIFIERS,
3145    }
3146
3147    def unnest(self):
3148        """
3149        Returns the first non subquery.
3150        """
3151        expression = self
3152        while isinstance(expression, Subquery):
3153            expression = expression.this
3154        return expression
3155
3156    @property
3157    def is_star(self) -> bool:
3158        return self.this.is_star
3159
3160    @property
3161    def output_name(self) -> str:
3162        return self.alias
3163
3164
3165class TableSample(Expression):
3166    arg_types = {
3167        "this": False,
3168        "method": False,
3169        "bucket_numerator": False,
3170        "bucket_denominator": False,
3171        "bucket_field": False,
3172        "percent": False,
3173        "rows": False,
3174        "size": False,
3175        "seed": False,
3176        "kind": False,
3177    }
3178
3179
3180class Tag(Expression):
3181    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3182
3183    arg_types = {
3184        "this": False,
3185        "prefix": False,
3186        "postfix": False,
3187    }
3188
3189
3190# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax
3191# https://duckdb.org/docs/sql/statements/pivot
3192class Pivot(Expression):
3193    arg_types = {
3194        "this": False,
3195        "alias": False,
3196        "expressions": True,
3197        "field": False,
3198        "unpivot": False,
3199        "using": False,
3200        "group": False,
3201        "columns": False,
3202    }
3203
3204
3205class Window(Expression):
3206    arg_types = {
3207        "this": True,
3208        "partition_by": False,
3209        "order": False,
3210        "spec": False,
3211        "alias": False,
3212        "over": False,
3213        "first": False,
3214    }
3215
3216
3217class WindowSpec(Expression):
3218    arg_types = {
3219        "kind": False,
3220        "start": False,
3221        "start_side": False,
3222        "end": False,
3223        "end_side": False,
3224    }
3225
3226
3227class Where(Expression):
3228    pass
3229
3230
3231class Star(Expression):
3232    arg_types = {"except": False, "replace": False}
3233
3234    @property
3235    def name(self) -> str:
3236        return "*"
3237
3238    @property
3239    def output_name(self) -> str:
3240        return self.name
3241
3242
3243class Parameter(Condition):
3244    arg_types = {"this": True, "wrapped": False}
3245
3246
3247class SessionParameter(Condition):
3248    arg_types = {"this": True, "kind": False}
3249
3250
3251class Placeholder(Condition):
3252    arg_types = {"this": False, "kind": False}
3253
3254
3255class Null(Condition):
3256    arg_types: t.Dict[str, t.Any] = {}
3257
3258    @property
3259    def name(self) -> str:
3260        return "NULL"
3261
3262
3263class Boolean(Condition):
3264    pass
3265
3266
3267class DataTypeSize(Expression):
3268    arg_types = {"this": True, "expression": False}
3269
3270
3271class DataType(Expression):
3272    arg_types = {
3273        "this": True,
3274        "expressions": False,
3275        "nested": False,
3276        "values": False,
3277        "prefix": False,
3278    }
3279
3280    class Type(AutoName):
3281        ARRAY = auto()
3282        BIGDECIMAL = auto()
3283        BIGINT = auto()
3284        BIGSERIAL = auto()
3285        BINARY = auto()
3286        BIT = auto()
3287        BOOLEAN = auto()
3288        CHAR = auto()
3289        DATE = auto()
3290        DATETIME = auto()
3291        DATETIME64 = auto()
3292        ENUM = auto()
3293        INT4RANGE = auto()
3294        INT4MULTIRANGE = auto()
3295        INT8RANGE = auto()
3296        INT8MULTIRANGE = auto()
3297        NUMRANGE = auto()
3298        NUMMULTIRANGE = auto()
3299        TSRANGE = auto()
3300        TSMULTIRANGE = auto()
3301        TSTZRANGE = auto()
3302        TSTZMULTIRANGE = auto()
3303        DATERANGE = auto()
3304        DATEMULTIRANGE = auto()
3305        DECIMAL = auto()
3306        DOUBLE = auto()
3307        FLOAT = auto()
3308        GEOGRAPHY = auto()
3309        GEOMETRY = auto()
3310        HLLSKETCH = auto()
3311        HSTORE = auto()
3312        IMAGE = auto()
3313        INET = auto()
3314        INT = auto()
3315        INT128 = auto()
3316        INT256 = auto()
3317        INTERVAL = auto()
3318        JSON = auto()
3319        JSONB = auto()
3320        LONGBLOB = auto()
3321        LONGTEXT = auto()
3322        MAP = auto()
3323        MEDIUMBLOB = auto()
3324        MEDIUMTEXT = auto()
3325        MONEY = auto()
3326        NCHAR = auto()
3327        NULL = auto()
3328        NULLABLE = auto()
3329        NVARCHAR = auto()
3330        OBJECT = auto()
3331        ROWVERSION = auto()
3332        SERIAL = auto()
3333        SET = auto()
3334        SMALLINT = auto()
3335        SMALLMONEY = auto()
3336        SMALLSERIAL = auto()
3337        STRUCT = auto()
3338        SUPER = auto()
3339        TEXT = auto()
3340        TIME = auto()
3341        TIMESTAMP = auto()
3342        TIMESTAMPTZ = auto()
3343        TIMESTAMPLTZ = auto()
3344        TINYINT = auto()
3345        UBIGINT = auto()
3346        UINT = auto()
3347        USMALLINT = auto()
3348        UTINYINT = auto()
3349        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3350        UINT128 = auto()
3351        UINT256 = auto()
3352        UNIQUEIDENTIFIER = auto()
3353        USERDEFINED = "USER-DEFINED"
3354        UUID = auto()
3355        VARBINARY = auto()
3356        VARCHAR = auto()
3357        VARIANT = auto()
3358        XML = auto()
3359
3360    TEXT_TYPES = {
3361        Type.CHAR,
3362        Type.NCHAR,
3363        Type.VARCHAR,
3364        Type.NVARCHAR,
3365        Type.TEXT,
3366    }
3367
3368    INTEGER_TYPES = {
3369        Type.INT,
3370        Type.TINYINT,
3371        Type.SMALLINT,
3372        Type.BIGINT,
3373        Type.INT128,
3374        Type.INT256,
3375    }
3376
3377    FLOAT_TYPES = {
3378        Type.FLOAT,
3379        Type.DOUBLE,
3380    }
3381
3382    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3383
3384    TEMPORAL_TYPES = {
3385        Type.TIME,
3386        Type.TIMESTAMP,
3387        Type.TIMESTAMPTZ,
3388        Type.TIMESTAMPLTZ,
3389        Type.DATE,
3390        Type.DATETIME,
3391        Type.DATETIME64,
3392    }
3393
3394    META_TYPES = {"UNKNOWN", "NULL"}
3395
3396    @classmethod
3397    def build(
3398        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3399    ) -> DataType:
3400        from sqlglot import parse_one
3401
3402        if isinstance(dtype, str):
3403            upper = dtype.upper()
3404            if upper in DataType.META_TYPES:
3405                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3406            else:
3407                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3408
3409            if data_type_exp is None:
3410                raise ValueError(f"Unparsable data type value: {dtype}")
3411        elif isinstance(dtype, DataType.Type):
3412            data_type_exp = DataType(this=dtype)
3413        elif isinstance(dtype, DataType):
3414            return dtype
3415        else:
3416            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3417
3418        return DataType(**{**data_type_exp.args, **kwargs})
3419
3420    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3421        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
3422
3423
3424# https://www.postgresql.org/docs/15/datatype-pseudo.html
3425class PseudoType(Expression):
3426    pass
3427
3428
3429# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3430class SubqueryPredicate(Predicate):
3431    pass
3432
3433
3434class All(SubqueryPredicate):
3435    pass
3436
3437
3438class Any(SubqueryPredicate):
3439    pass
3440
3441
3442class Exists(SubqueryPredicate):
3443    pass
3444
3445
3446# Commands to interact with the databases or engines. For most of the command
3447# expressions we parse whatever comes after the command's name as a string.
3448class Command(Expression):
3449    arg_types = {"this": True, "expression": False}
3450
3451
3452class Transaction(Expression):
3453    arg_types = {"this": False, "modes": False}
3454
3455
3456class Commit(Expression):
3457    arg_types = {"chain": False}
3458
3459
3460class Rollback(Expression):
3461    arg_types = {"savepoint": False}
3462
3463
3464class AlterTable(Expression):
3465    arg_types = {"this": True, "actions": True, "exists": False}
3466
3467
3468class AddConstraint(Expression):
3469    arg_types = {"this": False, "expression": False, "enforced": False}
3470
3471
3472class DropPartition(Expression):
3473    arg_types = {"expressions": True, "exists": False}
3474
3475
3476# Binary expressions like (ADD a b)
3477class Binary(Condition):
3478    arg_types = {"this": True, "expression": True}
3479
3480    @property
3481    def left(self):
3482        return self.this
3483
3484    @property
3485    def right(self):
3486        return self.expression
3487
3488
3489class Add(Binary):
3490    pass
3491
3492
3493class Connector(Binary):
3494    pass
3495
3496
3497class And(Connector):
3498    pass
3499
3500
3501class Or(Connector):
3502    pass
3503
3504
3505class BitwiseAnd(Binary):
3506    pass
3507
3508
3509class BitwiseLeftShift(Binary):
3510    pass
3511
3512
3513class BitwiseOr(Binary):
3514    pass
3515
3516
3517class BitwiseRightShift(Binary):
3518    pass
3519
3520
3521class BitwiseXor(Binary):
3522    pass
3523
3524
3525class Div(Binary):
3526    pass
3527
3528
3529class Overlaps(Binary):
3530    pass
3531
3532
3533class Dot(Binary):
3534    @property
3535    def name(self) -> str:
3536        return self.expression.name
3537
3538    @property
3539    def output_name(self) -> str:
3540        return self.name
3541
3542    @classmethod
3543    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3544        """Build a Dot object with a sequence of expressions."""
3545        if len(expressions) < 2:
3546            raise ValueError(f"Dot requires >= 2 expressions.")
3547
3548        a, b, *expressions = expressions
3549        dot = Dot(this=a, expression=b)
3550
3551        for expression in expressions:
3552            dot = Dot(this=dot, expression=expression)
3553
3554        return dot
3555
3556
3557class DPipe(Binary):
3558    pass
3559
3560
3561class SafeDPipe(DPipe):
3562    pass
3563
3564
3565class EQ(Binary, Predicate):
3566    pass
3567
3568
3569class NullSafeEQ(Binary, Predicate):
3570    pass
3571
3572
3573class NullSafeNEQ(Binary, Predicate):
3574    pass
3575
3576
3577class Distance(Binary):
3578    pass
3579
3580
3581class Escape(Binary):
3582    pass
3583
3584
3585class Glob(Binary, Predicate):
3586    pass
3587
3588
3589class GT(Binary, Predicate):
3590    pass
3591
3592
3593class GTE(Binary, Predicate):
3594    pass
3595
3596
3597class ILike(Binary, Predicate):
3598    pass
3599
3600
3601class ILikeAny(Binary, Predicate):
3602    pass
3603
3604
3605class IntDiv(Binary):
3606    pass
3607
3608
3609class Is(Binary, Predicate):
3610    pass
3611
3612
3613class Kwarg(Binary):
3614    """Kwarg in special functions like func(kwarg => y)."""
3615
3616
3617class Like(Binary, Predicate):
3618    pass
3619
3620
3621class LikeAny(Binary, Predicate):
3622    pass
3623
3624
3625class LT(Binary, Predicate):
3626    pass
3627
3628
3629class LTE(Binary, Predicate):
3630    pass
3631
3632
3633class Mod(Binary):
3634    pass
3635
3636
3637class Mul(Binary):
3638    pass
3639
3640
3641class NEQ(Binary, Predicate):
3642    pass
3643
3644
3645class SimilarTo(Binary, Predicate):
3646    pass
3647
3648
3649class Slice(Binary):
3650    arg_types = {"this": False, "expression": False}
3651
3652
3653class Sub(Binary):
3654    pass
3655
3656
3657class ArrayOverlaps(Binary):
3658    pass
3659
3660
3661# Unary Expressions
3662# (NOT a)
3663class Unary(Condition):
3664    pass
3665
3666
3667class BitwiseNot(Unary):
3668    pass
3669
3670
3671class Not(Unary):
3672    pass
3673
3674
3675class Paren(Unary):
3676    arg_types = {"this": True, "with": False}
3677
3678    @property
3679    def output_name(self) -> str:
3680        return self.this.name
3681
3682
3683class Neg(Unary):
3684    pass
3685
3686
3687class Alias(Expression):
3688    arg_types = {"this": True, "alias": False}
3689
3690    @property
3691    def output_name(self) -> str:
3692        return self.alias
3693
3694
3695class Aliases(Expression):
3696    arg_types = {"this": True, "expressions": True}
3697
3698    @property
3699    def aliases(self):
3700        return self.expressions
3701
3702
3703class AtTimeZone(Expression):
3704    arg_types = {"this": True, "zone": True}
3705
3706
3707class Between(Predicate):
3708    arg_types = {"this": True, "low": True, "high": True}
3709
3710
3711class Bracket(Condition):
3712    arg_types = {"this": True, "expressions": True}
3713
3714
3715class SafeBracket(Bracket):
3716    """Represents array lookup where OOB index yields NULL instead of causing a failure."""
3717
3718
3719class Distinct(Expression):
3720    arg_types = {"expressions": False, "on": False}
3721
3722
3723class In(Predicate):
3724    arg_types = {
3725        "this": True,
3726        "expressions": False,
3727        "query": False,
3728        "unnest": False,
3729        "field": False,
3730        "is_global": False,
3731    }
3732
3733
3734class TimeUnit(Expression):
3735    """Automatically converts unit arg into a var."""
3736
3737    arg_types = {"unit": False}
3738
3739    def __init__(self, **args):
3740        unit = args.get("unit")
3741        if isinstance(unit, (Column, Literal)):
3742            args["unit"] = Var(this=unit.name)
3743        elif isinstance(unit, Week):
3744            unit.set("this", Var(this=unit.this.name))
3745
3746        super().__init__(**args)
3747
3748
3749class Interval(TimeUnit):
3750    arg_types = {"this": False, "unit": False}
3751
3752    @property
3753    def unit(self) -> t.Optional[Var]:
3754        return self.args.get("unit")
3755
3756
3757class IgnoreNulls(Expression):
3758    pass
3759
3760
3761class RespectNulls(Expression):
3762    pass
3763
3764
3765# Functions
3766class Func(Condition):
3767    """
3768    The base class for all function expressions.
3769
3770    Attributes:
3771        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3772            treated as a variable length argument and the argument's value will be stored as a list.
3773        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3774            for this function expression. These values are used to map this node to a name during parsing
3775            as well as to provide the function's name during SQL string generation. By default the SQL
3776            name is set to the expression's class name transformed to snake case.
3777    """
3778
3779    is_var_len_args = False
3780
3781    @classmethod
3782    def from_arg_list(cls, args):
3783        if cls.is_var_len_args:
3784            all_arg_keys = list(cls.arg_types)
3785            # If this function supports variable length argument treat the last argument as such.
3786            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3787            num_non_var = len(non_var_len_arg_keys)
3788
3789            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3790            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3791        else:
3792            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3793
3794        return cls(**args_dict)
3795
3796    @classmethod
3797    def sql_names(cls):
3798        if cls is Func:
3799            raise NotImplementedError(
3800                "SQL name is only supported by concrete function implementations"
3801            )
3802        if "_sql_names" not in cls.__dict__:
3803            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3804        return cls._sql_names
3805
3806    @classmethod
3807    def sql_name(cls):
3808        return cls.sql_names()[0]
3809
3810    @classmethod
3811    def default_parser_mappings(cls):
3812        return {name: cls.from_arg_list for name in cls.sql_names()}
3813
3814
3815class AggFunc(Func):
3816    pass
3817
3818
3819class ParameterizedAgg(AggFunc):
3820    arg_types = {"this": True, "expressions": True, "params": True}
3821
3822
3823class Abs(Func):
3824    pass
3825
3826
3827class Anonymous(Func):
3828    arg_types = {"this": True, "expressions": False}
3829    is_var_len_args = True
3830
3831
3832# https://docs.snowflake.com/en/sql-reference/functions/hll
3833# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3834class Hll(AggFunc):
3835    arg_types = {"this": True, "expressions": False}
3836    is_var_len_args = True
3837
3838
3839class ApproxDistinct(AggFunc):
3840    arg_types = {"this": True, "accuracy": False}
3841    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
3842
3843
3844class Array(Func):
3845    arg_types = {"expressions": False}
3846    is_var_len_args = True
3847
3848
3849# https://docs.snowflake.com/en/sql-reference/functions/to_char
3850class ToChar(Func):
3851    arg_types = {"this": True, "format": False}
3852
3853
3854class GenerateSeries(Func):
3855    arg_types = {"start": True, "end": True, "step": False}
3856
3857
3858class ArrayAgg(AggFunc):
3859    pass
3860
3861
3862class ArrayAll(Func):
3863    arg_types = {"this": True, "expression": True}
3864
3865
3866class ArrayAny(Func):
3867    arg_types = {"this": True, "expression": True}
3868
3869
3870class ArrayConcat(Func):
3871    arg_types = {"this": True, "expressions": False}
3872    is_var_len_args = True
3873
3874
3875class ArrayContains(Binary, Func):
3876    pass
3877
3878
3879class ArrayContained(Binary):
3880    pass
3881
3882
3883class ArrayFilter(Func):
3884    arg_types = {"this": True, "expression": True}
3885    _sql_names = ["FILTER", "ARRAY_FILTER"]
3886
3887
3888class ArrayJoin(Func):
3889    arg_types = {"this": True, "expression": True, "null": False}
3890
3891
3892class ArraySize(Func):
3893    arg_types = {"this": True, "expression": False}
3894
3895
3896class ArraySort(Func):
3897    arg_types = {"this": True, "expression": False}
3898
3899
3900class ArraySum(Func):
3901    pass
3902
3903
3904class ArrayUnionAgg(AggFunc):
3905    pass
3906
3907
3908class Avg(AggFunc):
3909    pass
3910
3911
3912class AnyValue(AggFunc):
3913    pass
3914
3915
3916class Case(Func):
3917    arg_types = {"this": False, "ifs": True, "default": False}
3918
3919    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3920        instance = _maybe_copy(self, copy)
3921        instance.append(
3922            "ifs",
3923            If(
3924                this=maybe_parse(condition, copy=copy, **opts),
3925                true=maybe_parse(then, copy=copy, **opts),
3926            ),
3927        )
3928        return instance
3929
3930    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3931        instance = _maybe_copy(self, copy)
3932        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3933        return instance
3934
3935
3936class Cast(Func):
3937    arg_types = {"this": True, "to": True}
3938
3939    @property
3940    def name(self) -> str:
3941        return self.this.name
3942
3943    @property
3944    def to(self) -> DataType:
3945        return self.args["to"]
3946
3947    @property
3948    def output_name(self) -> str:
3949        return self.name
3950
3951    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3952        return self.to.is_type(*dtypes)
3953
3954
3955class CastToStrType(Func):
3956    arg_types = {"this": True, "expression": True}
3957
3958
3959class Collate(Binary):
3960    pass
3961
3962
3963class TryCast(Cast):
3964    pass
3965
3966
3967class Ceil(Func):
3968    arg_types = {"this": True, "decimals": False}
3969    _sql_names = ["CEIL", "CEILING"]
3970
3971
3972class Coalesce(Func):
3973    arg_types = {"this": True, "expressions": False}
3974    is_var_len_args = True
3975    _sql_names = ["COALESCE", "IFNULL", "NVL"]
3976
3977
3978class Concat(Func):
3979    arg_types = {"expressions": True}
3980    is_var_len_args = True
3981
3982
3983class SafeConcat(Concat):
3984    pass
3985
3986
3987class ConcatWs(Concat):
3988    _sql_names = ["CONCAT_WS"]
3989
3990
3991class Count(AggFunc):
3992    arg_types = {"this": False, "expressions": False}
3993    is_var_len_args = True
3994
3995
3996class CountIf(AggFunc):
3997    pass
3998
3999
4000class CurrentDate(Func):
4001    arg_types = {"this": False}
4002
4003
4004class CurrentDatetime(Func):
4005    arg_types = {"this": False}
4006
4007
4008class CurrentTime(Func):
4009    arg_types = {"this": False}
4010
4011
4012class CurrentTimestamp(Func):
4013    arg_types = {"this": False}
4014
4015
4016class CurrentUser(Func):
4017    arg_types = {"this": False}
4018
4019
4020class DateAdd(Func, TimeUnit):
4021    arg_types = {"this": True, "expression": True, "unit": False}
4022
4023
4024class DateSub(Func, TimeUnit):
4025    arg_types = {"this": True, "expression": True, "unit": False}
4026
4027
4028class DateDiff(Func, TimeUnit):
4029    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4030    arg_types = {"this": True, "expression": True, "unit": False}
4031
4032
4033class DateTrunc(Func):
4034    arg_types = {"unit": True, "this": True, "zone": False}
4035
4036
4037class DatetimeAdd(Func, TimeUnit):
4038    arg_types = {"this": True, "expression": True, "unit": False}
4039
4040
4041class DatetimeSub(Func, TimeUnit):
4042    arg_types = {"this": True, "expression": True, "unit": False}
4043
4044
4045class DatetimeDiff(Func, TimeUnit):
4046    arg_types = {"this": True, "expression": True, "unit": False}
4047
4048
4049class DatetimeTrunc(Func, TimeUnit):
4050    arg_types = {"this": True, "unit": True, "zone": False}
4051
4052
4053class DayOfWeek(Func):
4054    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
4055
4056
4057class DayOfMonth(Func):
4058    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
4059
4060
4061class DayOfYear(Func):
4062    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
4063
4064
4065class WeekOfYear(Func):
4066    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
4067
4068
4069class LastDateOfMonth(Func):
4070    pass
4071
4072
4073class Extract(Func):
4074    arg_types = {"this": True, "expression": True}
4075
4076
4077class TimestampAdd(Func, TimeUnit):
4078    arg_types = {"this": True, "expression": True, "unit": False}
4079
4080
4081class TimestampSub(Func, TimeUnit):
4082    arg_types = {"this": True, "expression": True, "unit": False}
4083
4084
4085class TimestampDiff(Func, TimeUnit):
4086    arg_types = {"this": True, "expression": True, "unit": False}
4087
4088
4089class TimestampTrunc(Func, TimeUnit):
4090    arg_types = {"this": True, "unit": True, "zone": False}
4091
4092
4093class TimeAdd(Func, TimeUnit):
4094    arg_types = {"this": True, "expression": True, "unit": False}
4095
4096
4097class TimeSub(Func, TimeUnit):
4098    arg_types = {"this": True, "expression": True, "unit": False}
4099
4100
4101class TimeDiff(Func, TimeUnit):
4102    arg_types = {"this": True, "expression": True, "unit": False}
4103
4104
4105class TimeTrunc(Func, TimeUnit):
4106    arg_types = {"this": True, "unit": True, "zone": False}
4107
4108
4109class DateFromParts(Func):
4110    _sql_names = ["DATEFROMPARTS"]
4111    arg_types = {"year": True, "month": True, "day": True}
4112
4113
4114class DateStrToDate(Func):
4115    pass
4116
4117
4118class DateToDateStr(Func):
4119    pass
4120
4121
4122class DateToDi(Func):
4123    pass
4124
4125
4126class Date(Func):
4127    arg_types = {"expressions": True}
4128    is_var_len_args = True
4129
4130
4131class Day(Func):
4132    pass
4133
4134
4135class Decode(Func):
4136    arg_types = {"this": True, "charset": True, "replace": False}
4137
4138
4139class DiToDate(Func):
4140    pass
4141
4142
4143class Encode(Func):
4144    arg_types = {"this": True, "charset": True}
4145
4146
4147class Exp(Func):
4148    pass
4149
4150
4151class Explode(Func):
4152    pass
4153
4154
4155class Floor(Func):
4156    arg_types = {"this": True, "decimals": False}
4157
4158
4159class FromBase64(Func):
4160    pass
4161
4162
4163class ToBase64(Func):
4164    pass
4165
4166
4167class Greatest(Func):
4168    arg_types = {"this": True, "expressions": False}
4169    is_var_len_args = True
4170
4171
4172class GroupConcat(Func):
4173    arg_types = {"this": True, "separator": False}
4174
4175
4176class Hex(Func):
4177    pass
4178
4179
4180class If(Func):
4181    arg_types = {"this": True, "true": True, "false": False}
4182
4183
4184class Initcap(Func):
4185    arg_types = {"this": True, "expression": False}
4186
4187
4188class JSONKeyValue(Expression):
4189    arg_types = {"this": True, "expression": True}
4190
4191
4192class JSONObject(Func):
4193    arg_types = {
4194        "expressions": False,
4195        "null_handling": False,
4196        "unique_keys": False,
4197        "return_type": False,
4198        "format_json": False,
4199        "encoding": False,
4200    }
4201
4202
4203class OpenJSONColumnDef(Expression):
4204    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
4205
4206
4207class OpenJSON(Func):
4208    arg_types = {"this": True, "path": False, "expressions": False}
4209
4210
4211class JSONBContains(Binary):
4212    _sql_names = ["JSONB_CONTAINS"]
4213
4214
4215class JSONExtract(Binary, Func):
4216    _sql_names = ["JSON_EXTRACT"]
4217
4218
4219class JSONExtractScalar(JSONExtract):
4220    _sql_names = ["JSON_EXTRACT_SCALAR"]
4221
4222
4223class JSONBExtract(JSONExtract):
4224    _sql_names = ["JSONB_EXTRACT"]
4225
4226
4227class JSONBExtractScalar(JSONExtract):
4228    _sql_names = ["JSONB_EXTRACT_SCALAR"]
4229
4230
4231class JSONFormat(Func):
4232    arg_types = {"this": False, "options": False}
4233    _sql_names = ["JSON_FORMAT"]
4234
4235
4236class Least(Func):
4237    arg_types = {"expressions": False}
4238    is_var_len_args = True
4239
4240
4241class Left(Func):
4242    arg_types = {"this": True, "expression": True}
4243
4244
4245class Right(Func):
4246    arg_types = {"this": True, "expression": True}
4247
4248
4249class Length(Func):
4250    _sql_names = ["LENGTH", "LEN"]
4251
4252
4253class Levenshtein(Func):
4254    arg_types = {
4255        "this": True,
4256        "expression": False,
4257        "ins_cost": False,
4258        "del_cost": False,
4259        "sub_cost": False,
4260    }
4261
4262
4263class Ln(Func):
4264    pass
4265
4266
4267class Log(Func):
4268    arg_types = {"this": True, "expression": False}
4269
4270
4271class Log2(Func):
4272    pass
4273
4274
4275class Log10(Func):
4276    pass
4277
4278
4279class LogicalOr(AggFunc):
4280    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
4281
4282
4283class LogicalAnd(AggFunc):
4284    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
4285
4286
4287class Lower(Func):
4288    _sql_names = ["LOWER", "LCASE"]
4289
4290
4291class Map(Func):
4292    arg_types = {"keys": False, "values": False}
4293
4294
4295class MapFromEntries(Func):
4296    pass
4297
4298
4299class StarMap(Func):
4300    pass
4301
4302
4303class VarMap(Func):
4304    arg_types = {"keys": True, "values": True}
4305    is_var_len_args = True
4306
4307    @property
4308    def keys(self) -> t.List[Expression]:
4309        return self.args["keys"].expressions
4310
4311    @property
4312    def values(self) -> t.List[Expression]:
4313        return self.args["values"].expressions
4314
4315
4316# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4317class MatchAgainst(Func):
4318    arg_types = {"this": True, "expressions": True, "modifier": False}
4319
4320
4321class Max(AggFunc):
4322    arg_types = {"this": True, "expressions": False}
4323    is_var_len_args = True
4324
4325
4326class MD5(Func):
4327    _sql_names = ["MD5"]
4328
4329
4330class Min(AggFunc):
4331    arg_types = {"this": True, "expressions": False}
4332    is_var_len_args = True
4333
4334
4335class Month(Func):
4336    pass
4337
4338
4339class Nvl2(Func):
4340    arg_types = {"this": True, "true": True, "false": False}
4341
4342
4343class Posexplode(Func):
4344    pass
4345
4346
4347class Pow(Binary, Func):
4348    _sql_names = ["POWER", "POW"]
4349
4350
4351class PercentileCont(AggFunc):
4352    arg_types = {"this": True, "expression": False}
4353
4354
4355class PercentileDisc(AggFunc):
4356    arg_types = {"this": True, "expression": False}
4357
4358
4359class Quantile(AggFunc):
4360    arg_types = {"this": True, "quantile": True}
4361
4362
4363class ApproxQuantile(Quantile):
4364    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4365
4366
4367class RangeN(Func):
4368    arg_types = {"this": True, "expressions": True, "each": False}
4369
4370
4371class ReadCSV(Func):
4372    _sql_names = ["READ_CSV"]
4373    is_var_len_args = True
4374    arg_types = {"this": True, "expressions": False}
4375
4376
4377class Reduce(Func):
4378    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4379
4380
4381class RegexpExtract(Func):
4382    arg_types = {
4383        "this": True,
4384        "expression": True,
4385        "position": False,
4386        "occurrence": False,
4387        "group": False,
4388    }
4389
4390
4391class RegexpLike(Func):
4392    arg_types = {"this": True, "expression": True, "flag": False}
4393
4394
4395class RegexpILike(Func):
4396    arg_types = {"this": True, "expression": True, "flag": False}
4397
4398
4399# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4400# limit is the number of times a pattern is applied
4401class RegexpSplit(Func):
4402    arg_types = {"this": True, "expression": True, "limit": False}
4403
4404
4405class Repeat(Func):
4406    arg_types = {"this": True, "times": True}
4407
4408
4409class Round(Func):
4410    arg_types = {"this": True, "decimals": False}
4411
4412
4413class RowNumber(Func):
4414    arg_types: t.Dict[str, t.Any] = {}
4415
4416
4417class SafeDivide(Func):
4418    arg_types = {"this": True, "expression": True}
4419
4420
4421class SetAgg(AggFunc):
4422    pass
4423
4424
4425class SHA(Func):
4426    _sql_names = ["SHA", "SHA1"]
4427
4428
4429class SHA2(Func):
4430    _sql_names = ["SHA2"]
4431    arg_types = {"this": True, "length": False}
4432
4433
4434class SortArray(Func):
4435    arg_types = {"this": True, "asc": False}
4436
4437
4438class Split(Func):
4439    arg_types = {"this": True, "expression": True, "limit": False}
4440
4441
4442# Start may be omitted in the case of postgres
4443# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4444class Substring(Func):
4445    arg_types = {"this": True, "start": False, "length": False}
4446
4447
4448class StandardHash(Func):
4449    arg_types = {"this": True, "expression": False}
4450
4451
4452class StrPosition(Func):
4453    arg_types = {
4454        "this": True,
4455        "substr": True,
4456        "position": False,
4457        "instance": False,
4458    }
4459
4460
4461class StrToDate(Func):
4462    arg_types = {"this": True, "format": True}
4463
4464
4465class StrToTime(Func):
4466    arg_types = {"this": True, "format": True}
4467
4468
4469# Spark allows unix_timestamp()
4470# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4471class StrToUnix(Func):
4472    arg_types = {"this": False, "format": False}
4473
4474
4475class NumberToStr(Func):
4476    arg_types = {"this": True, "format": True}
4477
4478
4479class FromBase(Func):
4480    arg_types = {"this": True, "expression": True}
4481
4482
4483class Struct(Func):
4484    arg_types = {"expressions": True}
4485    is_var_len_args = True
4486
4487
4488class StructExtract(Func):
4489    arg_types = {"this": True, "expression": True}
4490
4491
4492class Sum(AggFunc):
4493    pass
4494
4495
4496class Sqrt(Func):
4497    pass
4498
4499
4500class Stddev(AggFunc):
4501    pass
4502
4503
4504class StddevPop(AggFunc):
4505    pass
4506
4507
4508class StddevSamp(AggFunc):
4509    pass
4510
4511
4512class TimeToStr(Func):
4513    arg_types = {"this": True, "format": True}
4514
4515
4516class TimeToTimeStr(Func):
4517    pass
4518
4519
4520class TimeToUnix(Func):
4521    pass
4522
4523
4524class TimeStrToDate(Func):
4525    pass
4526
4527
4528class TimeStrToTime(Func):
4529    pass
4530
4531
4532class TimeStrToUnix(Func):
4533    pass
4534
4535
4536class Trim(Func):
4537    arg_types = {
4538        "this": True,
4539        "expression": False,
4540        "position": False,
4541        "collation": False,
4542    }
4543
4544
4545class TsOrDsAdd(Func, TimeUnit):
4546    arg_types = {"this": True, "expression": True, "unit": False}
4547
4548
4549class TsOrDsToDateStr(Func):
4550    pass
4551
4552
4553class TsOrDsToDate(Func):
4554    arg_types = {"this": True, "format": False}
4555
4556
4557class TsOrDiToDi(Func):
4558    pass
4559
4560
4561class Unhex(Func):
4562    pass
4563
4564
4565class UnixToStr(Func):
4566    arg_types = {"this": True, "format": False}
4567
4568
4569# https://prestodb.io/docs/current/functions/datetime.html
4570# presto has weird zone/hours/minutes
4571class UnixToTime(Func):
4572    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4573
4574    SECONDS = Literal.string("seconds")
4575    MILLIS = Literal.string("millis")
4576    MICROS = Literal.string("micros")
4577
4578
4579class UnixToTimeStr(Func):
4580    pass
4581
4582
4583class Upper(Func):
4584    _sql_names = ["UPPER", "UCASE"]
4585
4586
4587class Variance(AggFunc):
4588    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4589
4590
4591class VariancePop(AggFunc):
4592    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4593
4594
4595class Week(Func):
4596    arg_types = {"this": True, "mode": False}
4597
4598
4599class XMLTable(Func):
4600    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4601
4602
4603class Year(Func):
4604    pass
4605
4606
4607class Use(Expression):
4608    arg_types = {"this": True, "kind": False}
4609
4610
4611class Merge(Expression):
4612    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4613
4614
4615class When(Func):
4616    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4617
4618
4619# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4620# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4621class NextValueFor(Func):
4622    arg_types = {"this": True, "order": False}
4623
4624
4625def _norm_arg(arg):
4626    return arg.lower() if type(arg) is str else arg
4627
4628
4629ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4630
4631
4632# Helpers
4633@t.overload
4634def maybe_parse(
4635    sql_or_expression: ExpOrStr,
4636    *,
4637    into: t.Type[E],
4638    dialect: DialectType = None,
4639    prefix: t.Optional[str] = None,
4640    copy: bool = False,
4641    **opts,
4642) -> E:
4643    ...
4644
4645
4646@t.overload
4647def maybe_parse(
4648    sql_or_expression: str | E,
4649    *,
4650    into: t.Optional[IntoType] = None,
4651    dialect: DialectType = None,
4652    prefix: t.Optional[str] = None,
4653    copy: bool = False,
4654    **opts,
4655) -> E:
4656    ...
4657
4658
4659def maybe_parse(
4660    sql_or_expression: ExpOrStr,
4661    *,
4662    into: t.Optional[IntoType] = None,
4663    dialect: DialectType = None,
4664    prefix: t.Optional[str] = None,
4665    copy: bool = False,
4666    **opts,
4667) -> Expression:
4668    """Gracefully handle a possible string or expression.
4669
4670    Example:
4671        >>> maybe_parse("1")
4672        (LITERAL this: 1, is_string: False)
4673        >>> maybe_parse(to_identifier("x"))
4674        (IDENTIFIER this: x, quoted: False)
4675
4676    Args:
4677        sql_or_expression: the SQL code string or an expression
4678        into: the SQLGlot Expression to parse into
4679        dialect: the dialect used to parse the input expressions (in the case that an
4680            input expression is a SQL string).
4681        prefix: a string to prefix the sql with before it gets parsed
4682            (automatically includes a space)
4683        copy: whether or not to copy the expression.
4684        **opts: other options to use to parse the input expressions (again, in the case
4685            that an input expression is a SQL string).
4686
4687    Returns:
4688        Expression: the parsed or given expression.
4689    """
4690    if isinstance(sql_or_expression, Expression):
4691        if copy:
4692            return sql_or_expression.copy()
4693        return sql_or_expression
4694
4695    if sql_or_expression is None:
4696        raise ParseError(f"SQL cannot be None")
4697
4698    import sqlglot
4699
4700    sql = str(sql_or_expression)
4701    if prefix:
4702        sql = f"{prefix} {sql}"
4703
4704    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4705
4706
4707def _maybe_copy(instance: E, copy: bool = True) -> E:
4708    return instance.copy() if copy else instance
4709
4710
4711def _is_wrong_expression(expression, into):
4712    return isinstance(expression, Expression) and not isinstance(expression, into)
4713
4714
4715def _apply_builder(
4716    expression,
4717    instance,
4718    arg,
4719    copy=True,
4720    prefix=None,
4721    into=None,
4722    dialect=None,
4723    **opts,
4724):
4725    if _is_wrong_expression(expression, into):
4726        expression = into(this=expression)
4727    instance = _maybe_copy(instance, copy)
4728    expression = maybe_parse(
4729        sql_or_expression=expression,
4730        prefix=prefix,
4731        into=into,
4732        dialect=dialect,
4733        **opts,
4734    )
4735    instance.set(arg, expression)
4736    return instance
4737
4738
4739def _apply_child_list_builder(
4740    *expressions,
4741    instance,
4742    arg,
4743    append=True,
4744    copy=True,
4745    prefix=None,
4746    into=None,
4747    dialect=None,
4748    properties=None,
4749    **opts,
4750):
4751    instance = _maybe_copy(instance, copy)
4752    parsed = []
4753    for expression in expressions:
4754        if expression is not None:
4755            if _is_wrong_expression(expression, into):
4756                expression = into(expressions=[expression])
4757
4758            expression = maybe_parse(
4759                expression,
4760                into=into,
4761                dialect=dialect,
4762                prefix=prefix,
4763                **opts,
4764            )
4765            parsed.extend(expression.expressions)
4766
4767    existing = instance.args.get(arg)
4768    if append and existing:
4769        parsed = existing.expressions + parsed
4770
4771    child = into(expressions=parsed)
4772    for k, v in (properties or {}).items():
4773        child.set(k, v)
4774    instance.set(arg, child)
4775
4776    return instance
4777
4778
4779def _apply_list_builder(
4780    *expressions,
4781    instance,
4782    arg,
4783    append=True,
4784    copy=True,
4785    prefix=None,
4786    into=None,
4787    dialect=None,
4788    **opts,
4789):
4790    inst = _maybe_copy(instance, copy)
4791
4792    expressions = [
4793        maybe_parse(
4794            sql_or_expression=expression,
4795            into=into,
4796            prefix=prefix,
4797            dialect=dialect,
4798            **opts,
4799        )
4800        for expression in expressions
4801        if expression is not None
4802    ]
4803
4804    existing_expressions = inst.args.get(arg)
4805    if append and existing_expressions:
4806        expressions = existing_expressions + expressions
4807
4808    inst.set(arg, expressions)
4809    return inst
4810
4811
4812def _apply_conjunction_builder(
4813    *expressions,
4814    instance,
4815    arg,
4816    into=None,
4817    append=True,
4818    copy=True,
4819    dialect=None,
4820    **opts,
4821):
4822    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4823    if not expressions:
4824        return instance
4825
4826    inst = _maybe_copy(instance, copy)
4827
4828    existing = inst.args.get(arg)
4829    if append and existing is not None:
4830        expressions = [existing.this if into else existing] + list(expressions)
4831
4832    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4833
4834    inst.set(arg, into(this=node) if into else node)
4835    return inst
4836
4837
4838def _apply_cte_builder(
4839    instance: E,
4840    alias: ExpOrStr,
4841    as_: ExpOrStr,
4842    recursive: t.Optional[bool] = None,
4843    append: bool = True,
4844    dialect: DialectType = None,
4845    copy: bool = True,
4846    **opts,
4847) -> E:
4848    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
4849    as_expression = maybe_parse(as_, dialect=dialect, **opts)
4850    cte = CTE(this=as_expression, alias=alias_expression)
4851    return _apply_child_list_builder(
4852        cte,
4853        instance=instance,
4854        arg="with",
4855        append=append,
4856        copy=copy,
4857        into=With,
4858        properties={"recursive": recursive or False},
4859    )
4860
4861
4862def _combine(
4863    expressions: t.Sequence[t.Optional[ExpOrStr]],
4864    operator: t.Type[Connector],
4865    dialect: DialectType = None,
4866    copy: bool = True,
4867    **opts,
4868) -> Expression:
4869    conditions = [
4870        condition(expression, dialect=dialect, copy=copy, **opts)
4871        for expression in expressions
4872        if expression is not None
4873    ]
4874
4875    this, *rest = conditions
4876    if rest:
4877        this = _wrap(this, Connector)
4878    for expression in rest:
4879        this = operator(this=this, expression=_wrap(expression, Connector))
4880
4881    return this
4882
4883
4884def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4885    return Paren(this=expression) if isinstance(expression, kind) else expression
4886
4887
4888def union(
4889    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4890) -> Union:
4891    """
4892    Initializes a syntax tree from one UNION expression.
4893
4894    Example:
4895        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4896        'SELECT * FROM foo UNION SELECT * FROM bla'
4897
4898    Args:
4899        left: the SQL code string corresponding to the left-hand side.
4900            If an `Expression` instance is passed, it will be used as-is.
4901        right: the SQL code string corresponding to the right-hand side.
4902            If an `Expression` instance is passed, it will be used as-is.
4903        distinct: set the DISTINCT flag if and only if this is true.
4904        dialect: the dialect used to parse the input expression.
4905        opts: other options to use to parse the input expressions.
4906
4907    Returns:
4908        The new Union instance.
4909    """
4910    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4911    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4912
4913    return Union(this=left, expression=right, distinct=distinct)
4914
4915
4916def intersect(
4917    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4918) -> Intersect:
4919    """
4920    Initializes a syntax tree from one INTERSECT expression.
4921
4922    Example:
4923        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4924        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4925
4926    Args:
4927        left: the SQL code string corresponding to the left-hand side.
4928            If an `Expression` instance is passed, it will be used as-is.
4929        right: the SQL code string corresponding to the right-hand side.
4930            If an `Expression` instance is passed, it will be used as-is.
4931        distinct: set the DISTINCT flag if and only if this is true.
4932        dialect: the dialect used to parse the input expression.
4933        opts: other options to use to parse the input expressions.
4934
4935    Returns:
4936        The new Intersect instance.
4937    """
4938    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4939    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4940
4941    return Intersect(this=left, expression=right, distinct=distinct)
4942
4943
4944def except_(
4945    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4946) -> Except:
4947    """
4948    Initializes a syntax tree from one EXCEPT expression.
4949
4950    Example:
4951        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4952        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4953
4954    Args:
4955        left: the SQL code string corresponding to the left-hand side.
4956            If an `Expression` instance is passed, it will be used as-is.
4957        right: the SQL code string corresponding to the right-hand side.
4958            If an `Expression` instance is passed, it will be used as-is.
4959        distinct: set the DISTINCT flag if and only if this is true.
4960        dialect: the dialect used to parse the input expression.
4961        opts: other options to use to parse the input expressions.
4962
4963    Returns:
4964        The new Except instance.
4965    """
4966    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4967    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4968
4969    return Except(this=left, expression=right, distinct=distinct)
4970
4971
4972def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4973    """
4974    Initializes a syntax tree from one or multiple SELECT expressions.
4975
4976    Example:
4977        >>> select("col1", "col2").from_("tbl").sql()
4978        'SELECT col1, col2 FROM tbl'
4979
4980    Args:
4981        *expressions: the SQL code string to parse as the expressions of a
4982            SELECT statement. If an Expression instance is passed, this is used as-is.
4983        dialect: the dialect used to parse the input expressions (in the case that an
4984            input expression is a SQL string).
4985        **opts: other options to use to parse the input expressions (again, in the case
4986            that an input expression is a SQL string).
4987
4988    Returns:
4989        Select: the syntax tree for the SELECT statement.
4990    """
4991    return Select().select(*expressions, dialect=dialect, **opts)
4992
4993
4994def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4995    """
4996    Initializes a syntax tree from a FROM expression.
4997
4998    Example:
4999        >>> from_("tbl").select("col1", "col2").sql()
5000        'SELECT col1, col2 FROM tbl'
5001
5002    Args:
5003        *expression: the SQL code string to parse as the FROM expressions of a
5004            SELECT statement. If an Expression instance is passed, this is used as-is.
5005        dialect: the dialect used to parse the input expression (in the case that the
5006            input expression is a SQL string).
5007        **opts: other options to use to parse the input expressions (again, in the case
5008            that the input expression is a SQL string).
5009
5010    Returns:
5011        Select: the syntax tree for the SELECT statement.
5012    """
5013    return Select().from_(expression, dialect=dialect, **opts)
5014
5015
5016def update(
5017    table: str | Table,
5018    properties: dict,
5019    where: t.Optional[ExpOrStr] = None,
5020    from_: t.Optional[ExpOrStr] = None,
5021    dialect: DialectType = None,
5022    **opts,
5023) -> Update:
5024    """
5025    Creates an update statement.
5026
5027    Example:
5028        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5029        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5030
5031    Args:
5032        *properties: dictionary of properties to set which are
5033            auto converted to sql objects eg None -> NULL
5034        where: sql conditional parsed into a WHERE statement
5035        from_: sql statement parsed into a FROM statement
5036        dialect: the dialect used to parse the input expressions.
5037        **opts: other options to use to parse the input expressions.
5038
5039    Returns:
5040        Update: the syntax tree for the UPDATE statement.
5041    """
5042    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5043    update_expr.set(
5044        "expressions",
5045        [
5046            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5047            for k, v in properties.items()
5048        ],
5049    )
5050    if from_:
5051        update_expr.set(
5052            "from",
5053            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5054        )
5055    if isinstance(where, Condition):
5056        where = Where(this=where)
5057    if where:
5058        update_expr.set(
5059            "where",
5060            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5061        )
5062    return update_expr
5063
5064
5065def delete(
5066    table: ExpOrStr,
5067    where: t.Optional[ExpOrStr] = None,
5068    returning: t.Optional[ExpOrStr] = None,
5069    dialect: DialectType = None,
5070    **opts,
5071) -> Delete:
5072    """
5073    Builds a delete statement.
5074
5075    Example:
5076        >>> delete("my_table", where="id > 1").sql()
5077        'DELETE FROM my_table WHERE id > 1'
5078
5079    Args:
5080        where: sql conditional parsed into a WHERE statement
5081        returning: sql conditional parsed into a RETURNING statement
5082        dialect: the dialect used to parse the input expressions.
5083        **opts: other options to use to parse the input expressions.
5084
5085    Returns:
5086        Delete: the syntax tree for the DELETE statement.
5087    """
5088    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5089    if where:
5090        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5091    if returning:
5092        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5093    return delete_expr
5094
5095
5096def insert(
5097    expression: ExpOrStr,
5098    into: ExpOrStr,
5099    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5100    overwrite: t.Optional[bool] = None,
5101    dialect: DialectType = None,
5102    copy: bool = True,
5103    **opts,
5104) -> Insert:
5105    """
5106    Builds an INSERT statement.
5107
5108    Example:
5109        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5110        'INSERT INTO tbl VALUES (1, 2, 3)'
5111
5112    Args:
5113        expression: the sql string or expression of the INSERT statement
5114        into: the tbl to insert data to.
5115        columns: optionally the table's column names.
5116        overwrite: whether to INSERT OVERWRITE or not.
5117        dialect: the dialect used to parse the input expressions.
5118        copy: whether or not to copy the expression.
5119        **opts: other options to use to parse the input expressions.
5120
5121    Returns:
5122        Insert: the syntax tree for the INSERT statement.
5123    """
5124    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5125    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5126
5127    if columns:
5128        this = _apply_list_builder(
5129            *columns,
5130            instance=Schema(this=this),
5131            arg="expressions",
5132            into=Identifier,
5133            copy=False,
5134            dialect=dialect,
5135            **opts,
5136        )
5137
5138    return Insert(this=this, expression=expr, overwrite=overwrite)
5139
5140
5141def condition(
5142    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5143) -> Condition:
5144    """
5145    Initialize a logical condition expression.
5146
5147    Example:
5148        >>> condition("x=1").sql()
5149        'x = 1'
5150
5151        This is helpful for composing larger logical syntax trees:
5152        >>> where = condition("x=1")
5153        >>> where = where.and_("y=1")
5154        >>> Select().from_("tbl").select("*").where(where).sql()
5155        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5156
5157    Args:
5158        *expression: the SQL code string to parse.
5159            If an Expression instance is passed, this is used as-is.
5160        dialect: the dialect used to parse the input expression (in the case that the
5161            input expression is a SQL string).
5162        copy: Whether or not to copy `expression` (only applies to expressions).
5163        **opts: other options to use to parse the input expressions (again, in the case
5164            that the input expression is a SQL string).
5165
5166    Returns:
5167        The new Condition instance
5168    """
5169    return maybe_parse(
5170        expression,
5171        into=Condition,
5172        dialect=dialect,
5173        copy=copy,
5174        **opts,
5175    )
5176
5177
5178def and_(
5179    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5180) -> Condition:
5181    """
5182    Combine multiple conditions with an AND logical operator.
5183
5184    Example:
5185        >>> and_("x=1", and_("y=1", "z=1")).sql()
5186        'x = 1 AND (y = 1 AND z = 1)'
5187
5188    Args:
5189        *expressions: the SQL code strings to parse.
5190            If an Expression instance is passed, this is used as-is.
5191        dialect: the dialect used to parse the input expression.
5192        copy: whether or not to copy `expressions` (only applies to Expressions).
5193        **opts: other options to use to parse the input expressions.
5194
5195    Returns:
5196        And: the new condition
5197    """
5198    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
5199
5200
5201def or_(
5202    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5203) -> Condition:
5204    """
5205    Combine multiple conditions with an OR logical operator.
5206
5207    Example:
5208        >>> or_("x=1", or_("y=1", "z=1")).sql()
5209        'x = 1 OR (y = 1 OR z = 1)'
5210
5211    Args:
5212        *expressions: the SQL code strings to parse.
5213            If an Expression instance is passed, this is used as-is.
5214        dialect: the dialect used to parse the input expression.
5215        copy: whether or not to copy `expressions` (only applies to Expressions).
5216        **opts: other options to use to parse the input expressions.
5217
5218    Returns:
5219        Or: the new condition
5220    """
5221    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
5222
5223
5224def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5225    """
5226    Wrap a condition with a NOT operator.
5227
5228    Example:
5229        >>> not_("this_suit='black'").sql()
5230        "NOT this_suit = 'black'"
5231
5232    Args:
5233        expression: the SQL code string to parse.
5234            If an Expression instance is passed, this is used as-is.
5235        dialect: the dialect used to parse the input expression.
5236        copy: whether to copy the expression or not.
5237        **opts: other options to use to parse the input expressions.
5238
5239    Returns:
5240        The new condition.
5241    """
5242    this = condition(
5243        expression,
5244        dialect=dialect,
5245        copy=copy,
5246        **opts,
5247    )
5248    return Not(this=_wrap(this, Connector))
5249
5250
5251def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5252    """
5253    Wrap an expression in parentheses.
5254
5255    Example:
5256        >>> paren("5 + 3").sql()
5257        '(5 + 3)'
5258
5259    Args:
5260        expression: the SQL code string to parse.
5261            If an Expression instance is passed, this is used as-is.
5262        copy: whether to copy the expression or not.
5263
5264    Returns:
5265        The wrapped expression.
5266    """
5267    return Paren(this=maybe_parse(expression, copy=copy))
5268
5269
5270SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
5271
5272
5273@t.overload
5274def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
5275    ...
5276
5277
5278@t.overload
5279def to_identifier(
5280    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
5281) -> Identifier:
5282    ...
5283
5284
5285def to_identifier(name, quoted=None, copy=True):
5286    """Builds an identifier.
5287
5288    Args:
5289        name: The name to turn into an identifier.
5290        quoted: Whether or not force quote the identifier.
5291        copy: Whether or not to copy a passed in Identefier node.
5292
5293    Returns:
5294        The identifier ast node.
5295    """
5296
5297    if name is None:
5298        return None
5299
5300    if isinstance(name, Identifier):
5301        identifier = _maybe_copy(name, copy)
5302    elif isinstance(name, str):
5303        identifier = Identifier(
5304            this=name,
5305            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5306        )
5307    else:
5308        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5309    return identifier
5310
5311
5312INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
5313
5314
5315def to_interval(interval: str | Literal) -> Interval:
5316    """Builds an interval expression from a string like '1 day' or '5 months'."""
5317    if isinstance(interval, Literal):
5318        if not interval.is_string:
5319            raise ValueError("Invalid interval string.")
5320
5321        interval = interval.this
5322
5323    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5324
5325    if not interval_parts:
5326        raise ValueError("Invalid interval string.")
5327
5328    return Interval(
5329        this=Literal.string(interval_parts.group(1)),
5330        unit=Var(this=interval_parts.group(2)),
5331    )
5332
5333
5334@t.overload
5335def to_table(sql_path: str | Table, **kwargs) -> Table:
5336    ...
5337
5338
5339@t.overload
5340def to_table(sql_path: None, **kwargs) -> None:
5341    ...
5342
5343
5344def to_table(
5345    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5346) -> t.Optional[Table]:
5347    """
5348    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5349    If a table is passed in then that table is returned.
5350
5351    Args:
5352        sql_path: a `[catalog].[schema].[table]` string.
5353        dialect: the source dialect according to which the table name will be parsed.
5354        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5355
5356    Returns:
5357        A table expression.
5358    """
5359    if sql_path is None or isinstance(sql_path, Table):
5360        return sql_path
5361    if not isinstance(sql_path, str):
5362        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5363
5364    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5365    if table:
5366        for k, v in kwargs.items():
5367            table.set(k, v)
5368
5369    return table
5370
5371
5372def to_column(sql_path: str | Column, **kwargs) -> Column:
5373    """
5374    Create a column from a `[table].[column]` sql path. Schema is optional.
5375
5376    If a column is passed in then that column is returned.
5377
5378    Args:
5379        sql_path: `[table].[column]` string
5380    Returns:
5381        Table: A column expression
5382    """
5383    if sql_path is None or isinstance(sql_path, Column):
5384        return sql_path
5385    if not isinstance(sql_path, str):
5386        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5387    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
5388
5389
5390def alias_(
5391    expression: ExpOrStr,
5392    alias: str | Identifier,
5393    table: bool | t.Sequence[str | Identifier] = False,
5394    quoted: t.Optional[bool] = None,
5395    dialect: DialectType = None,
5396    copy: bool = True,
5397    **opts,
5398):
5399    """Create an Alias expression.
5400
5401    Example:
5402        >>> alias_('foo', 'bar').sql()
5403        'foo AS bar'
5404
5405        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5406        '(SELECT 1, 2) AS bar(a, b)'
5407
5408    Args:
5409        expression: the SQL code strings to parse.
5410            If an Expression instance is passed, this is used as-is.
5411        alias: the alias name to use. If the name has
5412            special characters it is quoted.
5413        table: Whether or not to create a table alias, can also be a list of columns.
5414        quoted: whether or not to quote the alias
5415        dialect: the dialect used to parse the input expression.
5416        copy: Whether or not to copy the expression.
5417        **opts: other options to use to parse the input expressions.
5418
5419    Returns:
5420        Alias: the aliased expression
5421    """
5422    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5423    alias = to_identifier(alias, quoted=quoted)
5424
5425    if table:
5426        table_alias = TableAlias(this=alias)
5427        exp.set("alias", table_alias)
5428
5429        if not isinstance(table, bool):
5430            for column in table:
5431                table_alias.append("columns", to_identifier(column, quoted=quoted))
5432
5433        return exp
5434
5435    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5436    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5437    # for the complete Window expression.
5438    #
5439    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5440
5441    if "alias" in exp.arg_types and not isinstance(exp, Window):
5442        exp.set("alias", alias)
5443        return exp
5444    return Alias(this=exp, alias=alias)
5445
5446
5447def subquery(
5448    expression: ExpOrStr,
5449    alias: t.Optional[Identifier | str] = None,
5450    dialect: DialectType = None,
5451    **opts,
5452) -> Select:
5453    """
5454    Build a subquery expression.
5455
5456    Example:
5457        >>> subquery('select x from tbl', 'bar').select('x').sql()
5458        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5459
5460    Args:
5461        expression: the SQL code strings to parse.
5462            If an Expression instance is passed, this is used as-is.
5463        alias: the alias name to use.
5464        dialect: the dialect used to parse the input expression.
5465        **opts: other options to use to parse the input expressions.
5466
5467    Returns:
5468        A new Select instance with the subquery expression included.
5469    """
5470
5471    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5472    return Select().from_(expression, dialect=dialect, **opts)
5473
5474
5475def column(
5476    col: str | Identifier,
5477    table: t.Optional[str | Identifier] = None,
5478    db: t.Optional[str | Identifier] = None,
5479    catalog: t.Optional[str | Identifier] = None,
5480    quoted: t.Optional[bool] = None,
5481) -> Column:
5482    """
5483    Build a Column.
5484
5485    Args:
5486        col: Column name.
5487        table: Table name.
5488        db: Database name.
5489        catalog: Catalog name.
5490        quoted: Whether to force quotes on the column's identifiers.
5491
5492    Returns:
5493        The new Column instance.
5494    """
5495    return Column(
5496        this=to_identifier(col, quoted=quoted),
5497        table=to_identifier(table, quoted=quoted),
5498        db=to_identifier(db, quoted=quoted),
5499        catalog=to_identifier(catalog, quoted=quoted),
5500    )
5501
5502
5503def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5504    """Cast an expression to a data type.
5505
5506    Example:
5507        >>> cast('x + 1', 'int').sql()
5508        'CAST(x + 1 AS INT)'
5509
5510    Args:
5511        expression: The expression to cast.
5512        to: The datatype to cast to.
5513
5514    Returns:
5515        The new Cast instance.
5516    """
5517    expression = maybe_parse(expression, **opts)
5518    return Cast(this=expression, to=DataType.build(to, **opts))
5519
5520
5521def table_(
5522    table: Identifier | str,
5523    db: t.Optional[Identifier | str] = None,
5524    catalog: t.Optional[Identifier | str] = None,
5525    quoted: t.Optional[bool] = None,
5526    alias: t.Optional[Identifier | str] = None,
5527) -> Table:
5528    """Build a Table.
5529
5530    Args:
5531        table: Table name.
5532        db: Database name.
5533        catalog: Catalog name.
5534        quote: Whether to force quotes on the table's identifiers.
5535        alias: Table's alias.
5536
5537    Returns:
5538        The new Table instance.
5539    """
5540    return Table(
5541        this=to_identifier(table, quoted=quoted),
5542        db=to_identifier(db, quoted=quoted),
5543        catalog=to_identifier(catalog, quoted=quoted),
5544        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5545    )
5546
5547
5548def values(
5549    values: t.Iterable[t.Tuple[t.Any, ...]],
5550    alias: t.Optional[str] = None,
5551    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5552) -> Values:
5553    """Build VALUES statement.
5554
5555    Example:
5556        >>> values([(1, '2')]).sql()
5557        "VALUES (1, '2')"
5558
5559    Args:
5560        values: values statements that will be converted to SQL
5561        alias: optional alias
5562        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5563         If either are provided then an alias is also required.
5564
5565    Returns:
5566        Values: the Values expression object
5567    """
5568    if columns and not alias:
5569        raise ValueError("Alias is required when providing columns")
5570
5571    return Values(
5572        expressions=[convert(tup) for tup in values],
5573        alias=(
5574            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5575            if columns
5576            else (TableAlias(this=to_identifier(alias)) if alias else None)
5577        ),
5578    )
5579
5580
5581def var(name: t.Optional[ExpOrStr]) -> Var:
5582    """Build a SQL variable.
5583
5584    Example:
5585        >>> repr(var('x'))
5586        '(VAR this: x)'
5587
5588        >>> repr(var(column('x', table='y')))
5589        '(VAR this: x)'
5590
5591    Args:
5592        name: The name of the var or an expression who's name will become the var.
5593
5594    Returns:
5595        The new variable node.
5596    """
5597    if not name:
5598        raise ValueError("Cannot convert empty name into var.")
5599
5600    if isinstance(name, Expression):
5601        name = name.name
5602    return Var(this=name)
5603
5604
5605def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5606    """Build ALTER TABLE... RENAME... expression
5607
5608    Args:
5609        old_name: The old name of the table
5610        new_name: The new name of the table
5611
5612    Returns:
5613        Alter table expression
5614    """
5615    old_table = to_table(old_name)
5616    new_table = to_table(new_name)
5617    return AlterTable(
5618        this=old_table,
5619        actions=[
5620            RenameTable(this=new_table),
5621        ],
5622    )
5623
5624
5625def convert(value: t.Any, copy: bool = False) -> Expression:
5626    """Convert a python value into an expression object.
5627
5628    Raises an error if a conversion is not possible.
5629
5630    Args:
5631        value: A python object.
5632        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5633
5634    Returns:
5635        Expression: the equivalent expression object.
5636    """
5637    if isinstance(value, Expression):
5638        return _maybe_copy(value, copy)
5639    if isinstance(value, str):
5640        return Literal.string(value)
5641    if isinstance(value, bool):
5642        return Boolean(this=value)
5643    if value is None or (isinstance(value, float) and math.isnan(value)):
5644        return NULL
5645    if isinstance(value, numbers.Number):
5646        return Literal.number(value)
5647    if isinstance(value, datetime.datetime):
5648        datetime_literal = Literal.string(
5649            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5650        )
5651        return TimeStrToTime(this=datetime_literal)
5652    if isinstance(value, datetime.date):
5653        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5654        return DateStrToDate(this=date_literal)
5655    if isinstance(value, tuple):
5656        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5657    if isinstance(value, list):
5658        return Array(expressions=[convert(v, copy=copy) for v in value])
5659    if isinstance(value, dict):
5660        return Map(
5661            keys=[convert(k, copy=copy) for k in value],
5662            values=[convert(v, copy=copy) for v in value.values()],
5663        )
5664    raise ValueError(f"Cannot convert {value}")
5665
5666
5667def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5668    """
5669    Replace children of an expression with the result of a lambda fun(child) -> exp.
5670    """
5671    for k, v in expression.args.items():
5672        is_list_arg = type(v) is list
5673
5674        child_nodes = v if is_list_arg else [v]
5675        new_child_nodes = []
5676
5677        for cn in child_nodes:
5678            if isinstance(cn, Expression):
5679                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5680                    new_child_nodes.append(child_node)
5681                    child_node.parent = expression
5682                    child_node.arg_key = k
5683            else:
5684                new_child_nodes.append(cn)
5685
5686        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5687
5688
5689def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5690    """
5691    Return all table names referenced through columns in an expression.
5692
5693    Example:
5694        >>> import sqlglot
5695        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5696        ['a', 'c']
5697
5698    Args:
5699        expression: expression to find table names.
5700        exclude: a table name to exclude
5701
5702    Returns:
5703        A list of unique names.
5704    """
5705    return {
5706        table
5707        for table in (column.table for column in expression.find_all(Column))
5708        if table and table != exclude
5709    }
5710
5711
5712def table_name(table: Table | str, dialect: DialectType = None) -> str:
5713    """Get the full name of a table as a string.
5714
5715    Args:
5716        table: Table expression node or string.
5717        dialect: The dialect to generate the table name for.
5718
5719    Examples:
5720        >>> from sqlglot import exp, parse_one
5721        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5722        'a.b.c'
5723
5724    Returns:
5725        The table name.
5726    """
5727
5728    table = maybe_parse(table, into=Table)
5729
5730    if not table:
5731        raise ValueError(f"Cannot parse {table}")
5732
5733    return ".".join(
5734        part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
5735        for part in table.parts
5736    )
5737
5738
5739def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5740    """Replace all tables in expression according to the mapping.
5741
5742    Args:
5743        expression: expression node to be transformed and replaced.
5744        mapping: mapping of table names.
5745        copy: whether or not to copy the expression.
5746
5747    Examples:
5748        >>> from sqlglot import exp, parse_one
5749        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5750        'SELECT * FROM c'
5751
5752    Returns:
5753        The mapped expression.
5754    """
5755
5756    def _replace_tables(node: Expression) -> Expression:
5757        if isinstance(node, Table):
5758            new_name = mapping.get(table_name(node))
5759            if new_name:
5760                return to_table(
5761                    new_name,
5762                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5763                )
5764        return node
5765
5766    return expression.transform(_replace_tables, copy=copy)
5767
5768
5769def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5770    """Replace placeholders in an expression.
5771
5772    Args:
5773        expression: expression node to be transformed and replaced.
5774        args: positional names that will substitute unnamed placeholders in the given order.
5775        kwargs: keyword arguments that will substitute named placeholders.
5776
5777    Examples:
5778        >>> from sqlglot import exp, parse_one
5779        >>> replace_placeholders(
5780        ...     parse_one("select * from :tbl where ? = ?"),
5781        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5782        ... ).sql()
5783        "SELECT * FROM foo WHERE str_col = 'b'"
5784
5785    Returns:
5786        The mapped expression.
5787    """
5788
5789    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5790        if isinstance(node, Placeholder):
5791            if node.name:
5792                new_name = kwargs.get(node.name)
5793                if new_name:
5794                    return convert(new_name)
5795            else:
5796                try:
5797                    return convert(next(args))
5798                except StopIteration:
5799                    pass
5800        return node
5801
5802    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5803
5804
5805def expand(
5806    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5807) -> Expression:
5808    """Transforms an expression by expanding all referenced sources into subqueries.
5809
5810    Examples:
5811        >>> from sqlglot import parse_one
5812        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5813        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5814
5815        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5816        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5817
5818    Args:
5819        expression: The expression to expand.
5820        sources: A dictionary of name to Subqueryables.
5821        copy: Whether or not to copy the expression during transformation. Defaults to True.
5822
5823    Returns:
5824        The transformed expression.
5825    """
5826
5827    def _expand(node: Expression):
5828        if isinstance(node, Table):
5829            name = table_name(node)
5830            source = sources.get(name)
5831            if source:
5832                subquery = source.subquery(node.alias or name)
5833                subquery.comments = [f"source: {name}"]
5834                return subquery.transform(_expand, copy=False)
5835        return node
5836
5837    return expression.transform(_expand, copy=copy)
5838
5839
5840def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5841    """
5842    Returns a Func expression.
5843
5844    Examples:
5845        >>> func("abs", 5).sql()
5846        'ABS(5)'
5847
5848        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5849        'CAST(5 AS DOUBLE)'
5850
5851    Args:
5852        name: the name of the function to build.
5853        args: the args used to instantiate the function of interest.
5854        dialect: the source dialect.
5855        kwargs: the kwargs used to instantiate the function of interest.
5856
5857    Note:
5858        The arguments `args` and `kwargs` are mutually exclusive.
5859
5860    Returns:
5861        An instance of the function of interest, or an anonymous function, if `name` doesn't
5862        correspond to an existing `sqlglot.expressions.Func` class.
5863    """
5864    if args and kwargs:
5865        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5866
5867    from sqlglot.dialects.dialect import Dialect
5868
5869    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5870    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5871
5872    parser = Dialect.get_or_raise(dialect)().parser()
5873    from_args_list = parser.FUNCTIONS.get(name.upper())
5874
5875    if from_args_list:
5876        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5877    else:
5878        kwargs = kwargs or {"expressions": converted}
5879        function = Anonymous(this=name, **kwargs)
5880
5881    for error_message in function.error_messages(converted):
5882        raise ValueError(error_message)
5883
5884    return function
5885
5886
5887def true() -> Boolean:
5888    """
5889    Returns a true Boolean expression.
5890    """
5891    return Boolean(this=True)
5892
5893
5894def false() -> Boolean:
5895    """
5896    Returns a false Boolean expression.
5897    """
5898    return Boolean(this=False)
5899
5900
5901def null() -> Null:
5902    """
5903    Returns a Null expression.
5904    """
5905    return Null()
5906
5907
5908# TODO: deprecate this
5909TRUE = Boolean(this=True)
5910FALSE = Boolean(this=False)
5911NULL = Null()
class Expression:
 55class Expression(metaclass=_Expression):
 56    """
 57    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 58    context, such as its child expressions, their names (arg keys), and whether a given child expression
 59    is optional or not.
 60
 61    Attributes:
 62        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 63            and representing expressions as strings.
 64        arg_types: determines what arguments (child nodes) are supported by an expression. It
 65            maps arg keys to booleans that indicate whether the corresponding args are optional.
 66        parent: a reference to the parent expression (or None, in case of root expressions).
 67        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 68            uses to refer to it.
 69        comments: a list of comments that are associated with a given expression. This is used in
 70            order to preserve comments when transpiling SQL code.
 71        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 72            optimizer, in order to enable some transformations that require type information.
 73
 74    Example:
 75        >>> class Foo(Expression):
 76        ...     arg_types = {"this": True, "expression": False}
 77
 78        The above definition informs us that Foo is an Expression that requires an argument called
 79        "this" and may also optionally receive an argument called "expression".
 80
 81    Args:
 82        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 83    """
 84
 85    key = "expression"
 86    arg_types = {"this": True}
 87    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 88
 89    def __init__(self, **args: t.Any):
 90        self.args: t.Dict[str, t.Any] = args
 91        self.parent: t.Optional[Expression] = None
 92        self.arg_key: t.Optional[str] = None
 93        self.comments: t.Optional[t.List[str]] = None
 94        self._type: t.Optional[DataType] = None
 95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 96        self._hash: t.Optional[int] = None
 97
 98        for arg_key, value in self.args.items():
 99            self._set_parent(arg_key, value)
100
101    def __eq__(self, other) -> bool:
102        return type(self) is type(other) and hash(self) == hash(other)
103
104    @property
105    def hashable_args(self) -> t.Any:
106        args = (self.args.get(k) for k in self.arg_types)
107
108        return tuple(
109            (tuple(_norm_arg(a) for a in arg) if arg else None)
110            if type(arg) is list
111            else (_norm_arg(arg) if arg is not None and arg is not False else None)
112            for arg in args
113        )
114
115    def __hash__(self) -> int:
116        if self._hash is not None:
117            return self._hash
118
119        return hash((self.__class__, self.hashable_args))
120
121    @property
122    def this(self):
123        """
124        Retrieves the argument with key "this".
125        """
126        return self.args.get("this")
127
128    @property
129    def expression(self):
130        """
131        Retrieves the argument with key "expression".
132        """
133        return self.args.get("expression")
134
135    @property
136    def expressions(self):
137        """
138        Retrieves the argument with key "expressions".
139        """
140        return self.args.get("expressions") or []
141
142    def text(self, key) -> str:
143        """
144        Returns a textual representation of the argument corresponding to "key". This can only be used
145        for args that are strings or leaf Expression instances, such as identifiers and literals.
146        """
147        field = self.args.get(key)
148        if isinstance(field, str):
149            return field
150        if isinstance(field, (Identifier, Literal, Var)):
151            return field.this
152        if isinstance(field, (Star, Null)):
153            return field.name
154        return ""
155
156    @property
157    def is_string(self) -> bool:
158        """
159        Checks whether a Literal expression is a string.
160        """
161        return isinstance(self, Literal) and self.args["is_string"]
162
163    @property
164    def is_number(self) -> bool:
165        """
166        Checks whether a Literal expression is a number.
167        """
168        return isinstance(self, Literal) and not self.args["is_string"]
169
170    @property
171    def is_int(self) -> bool:
172        """
173        Checks whether a Literal expression is an integer.
174        """
175        if self.is_number:
176            try:
177                int(self.name)
178                return True
179            except ValueError:
180                pass
181        return False
182
183    @property
184    def is_star(self) -> bool:
185        """Checks whether an expression is a star."""
186        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
187
188    @property
189    def alias(self) -> str:
190        """
191        Returns the alias of the expression, or an empty string if it's not aliased.
192        """
193        if isinstance(self.args.get("alias"), TableAlias):
194            return self.args["alias"].name
195        return self.text("alias")
196
197    @property
198    def name(self) -> str:
199        return self.text("this")
200
201    @property
202    def alias_or_name(self) -> str:
203        return self.alias or self.name
204
205    @property
206    def output_name(self) -> str:
207        """
208        Name of the output column if this expression is a selection.
209
210        If the Expression has no output name, an empty string is returned.
211
212        Example:
213            >>> from sqlglot import parse_one
214            >>> parse_one("SELECT a").expressions[0].output_name
215            'a'
216            >>> parse_one("SELECT b AS c").expressions[0].output_name
217            'c'
218            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
219            ''
220        """
221        return ""
222
223    @property
224    def type(self) -> t.Optional[DataType]:
225        return self._type
226
227    @type.setter
228    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
229        if dtype and not isinstance(dtype, DataType):
230            dtype = DataType.build(dtype)
231        self._type = dtype  # type: ignore
232
233    @property
234    def meta(self) -> t.Dict[str, t.Any]:
235        if self._meta is None:
236            self._meta = {}
237        return self._meta
238
239    def __deepcopy__(self, memo):
240        copy = self.__class__(**deepcopy(self.args))
241        if self.comments is not None:
242            copy.comments = deepcopy(self.comments)
243
244        if self._type is not None:
245            copy._type = self._type.copy()
246
247        if self._meta is not None:
248            copy._meta = deepcopy(self._meta)
249
250        return copy
251
252    def copy(self):
253        """
254        Returns a deep copy of the expression.
255        """
256        new = deepcopy(self)
257        new.parent = self.parent
258        return new
259
260    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
261        if self.comments is None:
262            self.comments = []
263        if comments:
264            self.comments.extend(comments)
265
266    def append(self, arg_key: str, value: t.Any) -> None:
267        """
268        Appends value to arg_key if it's a list or sets it as a new list.
269
270        Args:
271            arg_key (str): name of the list expression arg
272            value (Any): value to append to the list
273        """
274        if not isinstance(self.args.get(arg_key), list):
275            self.args[arg_key] = []
276        self.args[arg_key].append(value)
277        self._set_parent(arg_key, value)
278
279    def set(self, arg_key: str, value: t.Any) -> None:
280        """
281        Sets `arg_key` to `value`.
282
283        Args:
284            arg_key (str): name of the expression arg.
285            value: value to set the arg to.
286        """
287        self.args[arg_key] = value
288        self._set_parent(arg_key, value)
289
290    def _set_parent(self, arg_key: str, value: t.Any) -> None:
291        if hasattr(value, "parent"):
292            value.parent = self
293            value.arg_key = arg_key
294        elif type(value) is list:
295            for v in value:
296                if hasattr(v, "parent"):
297                    v.parent = self
298                    v.arg_key = arg_key
299
300    @property
301    def depth(self) -> int:
302        """
303        Returns the depth of this tree.
304        """
305        if self.parent:
306            return self.parent.depth + 1
307        return 0
308
309    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
310        """Yields the key and expression for all arguments, exploding list args."""
311        for k, vs in self.args.items():
312            if type(vs) is list:
313                for v in vs:
314                    if hasattr(v, "parent"):
315                        yield k, v
316            else:
317                if hasattr(vs, "parent"):
318                    yield k, vs
319
320    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
321        """
322        Returns the first node in this tree which matches at least one of
323        the specified types.
324
325        Args:
326            expression_types: the expression type(s) to match.
327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
328
329        Returns:
330            The node which matches the criteria or None if no such node was found.
331        """
332        return next(self.find_all(*expression_types, bfs=bfs), None)
333
334    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
335        """
336        Returns a generator object which visits all nodes in this tree and only
337        yields those that match at least one of the specified expression types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression
349
350    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)
364
365    @property
366    def parent_select(self) -> t.Optional[Select]:
367        """
368        Returns the parent select statement.
369        """
370        return self.find_ancestor(Select)
371
372    @property
373    def same_parent(self) -> bool:
374        """Returns if the parent is the same class as itself."""
375        return type(self.parent) is self.__class__
376
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression
385
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)
403
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)
419
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))
439
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression
448
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self
456
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())
462
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node
472
473    def __str__(self) -> str:
474        return self.sql()
475
476    def __repr__(self) -> str:
477        return self._to_s()
478
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)
493
494    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
495        indent = "" if not level else "\n"
496        indent += "".join(["  "] * level)
497        left = f"({self.key.upper()} "
498
499        args: t.Dict[str, t.Any] = {
500            k: ", ".join(
501                v._to_s(hide_missing=hide_missing, level=level + 1)
502                if hasattr(v, "_to_s")
503                else str(v)
504                for v in ensure_list(vs)
505                if v is not None
506            )
507            for k, vs in self.args.items()
508        }
509        args["comments"] = self.comments
510        args["type"] = self.type
511        args = {k: v for k, v in args.items() if v or not hide_missing}
512
513        right = ", ".join(f"{k}: {v}" for k, v in args.items())
514        right += ")"
515
516        return indent + left + right
517
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node
544
545    @t.overload
546    def replace(self, expression: E) -> E:
547        ...
548
549    @t.overload
550    def replace(self, expression: None) -> None:
551        ...
552
553    def replace(self, expression):
554        """
555        Swap out this expression with a new expression.
556
557        For example::
558
559            >>> tree = Select().select("x").from_("tbl")
560            >>> tree.find(Column).replace(Column(this="y"))
561            (COLUMN this: y)
562            >>> tree.sql()
563            'SELECT y FROM tbl'
564
565        Args:
566            expression: new node
567
568        Returns:
569            The new expression or expressions.
570        """
571        if not self.parent:
572            return expression
573
574        parent = self.parent
575        self.parent = None
576
577        replace_children(parent, lambda child: expression if child is self else child)
578        return expression
579
580    def pop(self: E) -> E:
581        """
582        Remove this expression from its AST.
583
584        Returns:
585            The popped expression.
586        """
587        self.replace(None)
588        return self
589
590    def assert_is(self, type_: t.Type[E]) -> E:
591        """
592        Assert that this `Expression` is an instance of `type_`.
593
594        If it is NOT an instance of `type_`, this raises an assertion error.
595        Otherwise, this returns this expression.
596
597        Examples:
598            This is useful for type security in chained expressions:
599
600            >>> import sqlglot
601            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
602            'SELECT x, z FROM y'
603        """
604        assert isinstance(self, type_)
605        return self
606
607    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
608        """
609        Checks if this expression is valid (e.g. all mandatory args are set).
610
611        Args:
612            args: a sequence of values that were used to instantiate a Func expression. This is used
613                to check that the provided arguments don't exceed the function argument limit.
614
615        Returns:
616            A list of error messages for all possible errors that were found.
617        """
618        errors: t.List[str] = []
619
620        for k in self.args:
621            if k not in self.arg_types:
622                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
623        for k, mandatory in self.arg_types.items():
624            v = self.args.get(k)
625            if mandatory and (v is None or (isinstance(v, list) and not v)):
626                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
627
628        if (
629            args
630            and isinstance(self, Func)
631            and len(args) > len(self.arg_types)
632            and not self.is_var_len_args
633        ):
634            errors.append(
635                f"The number of provided arguments ({len(args)}) is greater than "
636                f"the maximum number of supported arguments ({len(self.arg_types)})"
637            )
638
639        return errors
640
641    def dump(self):
642        """
643        Dump this Expression to a JSON-serializable dict.
644        """
645        from sqlglot.serde import dump
646
647        return dump(self)
648
649    @classmethod
650    def load(cls, obj):
651        """
652        Load a dict (as returned by `Expression.dump`) into an Expression instance.
653        """
654        from sqlglot.serde import load
655
656        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
89    def __init__(self, **args: t.Any):
90        self.args: t.Dict[str, t.Any] = args
91        self.parent: t.Optional[Expression] = None
92        self.arg_key: t.Optional[str] = None
93        self.comments: t.Optional[t.List[str]] = None
94        self._type: t.Optional[DataType] = None
95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
96        self._hash: t.Optional[int] = None
97
98        for arg_key, value in self.args.items():
99            self._set_parent(arg_key, value)
key = 'expression'
arg_types = {'this': True}
args: Dict[str, Any]
parent: Optional[sqlglot.expressions.Expression]
arg_key: Optional[str]
comments: Optional[List[str]]
hashable_args: Any
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
142    def text(self, key) -> str:
143        """
144        Returns a textual representation of the argument corresponding to "key". This can only be used
145        for args that are strings or leaf Expression instances, such as identifiers and literals.
146        """
147        field = self.args.get(key)
148        if isinstance(field, str):
149            return field
150        if isinstance(field, (Identifier, Literal, Var)):
151            return field.this
152        if isinstance(field, (Star, Null)):
153            return field.name
154        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

name: str
alias_or_name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
meta: Dict[str, Any]
def copy(self):
252    def copy(self):
253        """
254        Returns a deep copy of the expression.
255        """
256        new = deepcopy(self)
257        new.parent = self.parent
258        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
260    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
261        if self.comments is None:
262            self.comments = []
263        if comments:
264            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
266    def append(self, arg_key: str, value: t.Any) -> None:
267        """
268        Appends value to arg_key if it's a list or sets it as a new list.
269
270        Args:
271            arg_key (str): name of the list expression arg
272            value (Any): value to append to the list
273        """
274        if not isinstance(self.args.get(arg_key), list):
275            self.args[arg_key] = []
276        self.args[arg_key].append(value)
277        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key: str, value: Any) -> None:
279    def set(self, arg_key: str, value: t.Any) -> None:
280        """
281        Sets `arg_key` to `value`.
282
283        Args:
284            arg_key (str): name of the expression arg.
285            value: value to set the arg to.
286        """
287        self.args[arg_key] = value
288        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth: int

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
309    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
310        """Yields the key and expression for all arguments, exploding list args."""
311        for k, vs in self.args.items():
312            if type(vs) is list:
313                for v in vs:
314                    if hasattr(v, "parent"):
315                        yield k, v
316            else:
317                if hasattr(vs, "parent"):
318                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs: bool = True) -> Optional[~E]:
320    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
321        """
322        Returns the first node in this tree which matches at least one of
323        the specified types.
324
325        Args:
326            expression_types: the expression type(s) to match.
327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
328
329        Returns:
330            The node which matches the criteria or None if no such node was found.
331        """
332        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs: bool = True) -> Iterator[~E]:
334    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
335        """
336        Returns a generator object which visits all nodes in this tree and only
337        yields those that match at least one of the specified expression types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
350    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression

Returns the first non parenthesis child or self.

def unalias(self):
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
553    def replace(self, expression):
554        """
555        Swap out this expression with a new expression.
556
557        For example::
558
559            >>> tree = Select().select("x").from_("tbl")
560            >>> tree.find(Column).replace(Column(this="y"))
561            (COLUMN this: y)
562            >>> tree.sql()
563            'SELECT y FROM tbl'
564
565        Args:
566            expression: new node
567
568        Returns:
569            The new expression or expressions.
570        """
571        if not self.parent:
572            return expression
573
574        parent = self.parent
575        self.parent = None
576
577        replace_children(parent, lambda child: expression if child is self else child)
578        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression: new node
Returns:

The new expression or expressions.

def pop(self: ~E) -> ~E:
580    def pop(self: E) -> E:
581        """
582        Remove this expression from its AST.
583
584        Returns:
585            The popped expression.
586        """
587        self.replace(None)
588        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
590    def assert_is(self, type_: t.Type[E]) -> E:
591        """
592        Assert that this `Expression` is an instance of `type_`.
593
594        If it is NOT an instance of `type_`, this raises an assertion error.
595        Otherwise, this returns this expression.
596
597        Examples:
598            This is useful for type security in chained expressions:
599
600            >>> import sqlglot
601            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
602            'SELECT x, z FROM y'
603        """
604        assert isinstance(self, type_)
605        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
607    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
608        """
609        Checks if this expression is valid (e.g. all mandatory args are set).
610
611        Args:
612            args: a sequence of values that were used to instantiate a Func expression. This is used
613                to check that the provided arguments don't exceed the function argument limit.
614
615        Returns:
616            A list of error messages for all possible errors that were found.
617        """
618        errors: t.List[str] = []
619
620        for k in self.args:
621            if k not in self.arg_types:
622                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
623        for k, mandatory in self.arg_types.items():
624            v = self.args.get(k)
625            if mandatory and (v is None or (isinstance(v, list) and not v)):
626                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
627
628        if (
629            args
630            and isinstance(self, Func)
631            and len(args) > len(self.arg_types)
632            and not self.is_var_len_args
633        ):
634            errors.append(
635                f"The number of provided arguments ({len(args)}) is greater than "
636                f"the maximum number of supported arguments ({len(self.arg_types)})"
637            )
638
639        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
641    def dump(self):
642        """
643        Dump this Expression to a JSON-serializable dict.
644        """
645        from sqlglot.serde import dump
646
647        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
649    @classmethod
650    def load(cls, obj):
651        """
652        Load a dict (as returned by `Expression.dump`) into an Expression instance.
653        """
654        from sqlglot.serde import load
655
656        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

IntoType = typing.Union[str, typing.Type[sqlglot.expressions.Expression], typing.Collection[typing.Union[str, typing.Type[sqlglot.expressions.Expression]]]]
ExpOrStr = typing.Union[str, sqlglot.expressions.Expression]
class Condition(Expression):
667class Condition(Expression):
668    def and_(
669        self,
670        *expressions: t.Optional[ExpOrStr],
671        dialect: DialectType = None,
672        copy: bool = True,
673        **opts,
674    ) -> Condition:
675        """
676        AND this condition with one or multiple expressions.
677
678        Example:
679            >>> condition("x=1").and_("y=1").sql()
680            'x = 1 AND y = 1'
681
682        Args:
683            *expressions: the SQL code strings to parse.
684                If an `Expression` instance is passed, it will be used as-is.
685            dialect: the dialect used to parse the input expression.
686            copy: whether or not to copy the involved expressions (only applies to Expressions).
687            opts: other options to use to parse the input expressions.
688
689        Returns:
690            The new And condition.
691        """
692        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
693
694    def or_(
695        self,
696        *expressions: t.Optional[ExpOrStr],
697        dialect: DialectType = None,
698        copy: bool = True,
699        **opts,
700    ) -> Condition:
701        """
702        OR this condition with one or multiple expressions.
703
704        Example:
705            >>> condition("x=1").or_("y=1").sql()
706            'x = 1 OR y = 1'
707
708        Args:
709            *expressions: the SQL code strings to parse.
710                If an `Expression` instance is passed, it will be used as-is.
711            dialect: the dialect used to parse the input expression.
712            copy: whether or not to copy the involved expressions (only applies to Expressions).
713            opts: other options to use to parse the input expressions.
714
715        Returns:
716            The new Or condition.
717        """
718        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
719
720    def not_(self, copy: bool = True):
721        """
722        Wrap this condition with NOT.
723
724        Example:
725            >>> condition("x=1").not_().sql()
726            'NOT x = 1'
727
728        Args:
729            copy: whether or not to copy this object.
730
731        Returns:
732            The new Not instance.
733        """
734        return not_(self, copy=copy)
735
736    def as_(
737        self,
738        alias: str | Identifier,
739        quoted: t.Optional[bool] = None,
740        dialect: DialectType = None,
741        copy: bool = True,
742        **opts,
743    ) -> Alias:
744        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
745
746    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
747        this = self.copy()
748        other = convert(other, copy=True)
749        if not isinstance(this, klass) and not isinstance(other, klass):
750            this = _wrap(this, Binary)
751            other = _wrap(other, Binary)
752        if reverse:
753            return klass(this=other, expression=this)
754        return klass(this=this, expression=other)
755
756    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
757        return Bracket(
758            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
759        )
760
761    def isin(
762        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
763    ) -> In:
764        return In(
765            this=_maybe_copy(self, copy),
766            expressions=[convert(e, copy=copy) for e in expressions],
767            query=maybe_parse(query, copy=copy, **opts) if query else None,
768        )
769
770    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
771        return Between(
772            this=_maybe_copy(self, copy),
773            low=convert(low, copy=copy, **opts),
774            high=convert(high, copy=copy, **opts),
775        )
776
777    def is_(self, other: ExpOrStr) -> Is:
778        return self._binop(Is, other)
779
780    def like(self, other: ExpOrStr) -> Like:
781        return self._binop(Like, other)
782
783    def ilike(self, other: ExpOrStr) -> ILike:
784        return self._binop(ILike, other)
785
786    def eq(self, other: t.Any) -> EQ:
787        return self._binop(EQ, other)
788
789    def neq(self, other: t.Any) -> NEQ:
790        return self._binop(NEQ, other)
791
792    def rlike(self, other: ExpOrStr) -> RegexpLike:
793        return self._binop(RegexpLike, other)
794
795    def __lt__(self, other: t.Any) -> LT:
796        return self._binop(LT, other)
797
798    def __le__(self, other: t.Any) -> LTE:
799        return self._binop(LTE, other)
800
801    def __gt__(self, other: t.Any) -> GT:
802        return self._binop(GT, other)
803
804    def __ge__(self, other: t.Any) -> GTE:
805        return self._binop(GTE, other)
806
807    def __add__(self, other: t.Any) -> Add:
808        return self._binop(Add, other)
809
810    def __radd__(self, other: t.Any) -> Add:
811        return self._binop(Add, other, reverse=True)
812
813    def __sub__(self, other: t.Any) -> Sub:
814        return self._binop(Sub, other)
815
816    def __rsub__(self, other: t.Any) -> Sub:
817        return self._binop(Sub, other, reverse=True)
818
819    def __mul__(self, other: t.Any) -> Mul:
820        return self._binop(Mul, other)
821
822    def __rmul__(self, other: t.Any) -> Mul:
823        return self._binop(Mul, other, reverse=True)
824
825    def __truediv__(self, other: t.Any) -> Div:
826        return self._binop(Div, other)
827
828    def __rtruediv__(self, other: t.Any) -> Div:
829        return self._binop(Div, other, reverse=True)
830
831    def __floordiv__(self, other: t.Any) -> IntDiv:
832        return self._binop(IntDiv, other)
833
834    def __rfloordiv__(self, other: t.Any) -> IntDiv:
835        return self._binop(IntDiv, other, reverse=True)
836
837    def __mod__(self, other: t.Any) -> Mod:
838        return self._binop(Mod, other)
839
840    def __rmod__(self, other: t.Any) -> Mod:
841        return self._binop(Mod, other, reverse=True)
842
843    def __pow__(self, other: t.Any) -> Pow:
844        return self._binop(Pow, other)
845
846    def __rpow__(self, other: t.Any) -> Pow:
847        return self._binop(Pow, other, reverse=True)
848
849    def __and__(self, other: t.Any) -> And:
850        return self._binop(And, other)
851
852    def __rand__(self, other: t.Any) -> And:
853        return self._binop(And, other, reverse=True)
854
855    def __or__(self, other: t.Any) -> Or:
856        return self._binop(Or, other)
857
858    def __ror__(self, other: t.Any) -> Or:
859        return self._binop(Or, other, reverse=True)
860
861    def __neg__(self) -> Neg:
862        return Neg(this=_wrap(self.copy(), Binary))
863
864    def __invert__(self) -> Not:
865        return not_(self.copy())
def and_( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
668    def and_(
669        self,
670        *expressions: t.Optional[ExpOrStr],
671        dialect: DialectType = None,
672        copy: bool = True,
673        **opts,
674    ) -> Condition:
675        """
676        AND this condition with one or multiple expressions.
677
678        Example:
679            >>> condition("x=1").and_("y=1").sql()
680            'x = 1 AND y = 1'
681
682        Args:
683            *expressions: the SQL code strings to parse.
684                If an `Expression` instance is passed, it will be used as-is.
685            dialect: the dialect used to parse the input expression.
686            copy: whether or not to copy the involved expressions (only applies to Expressions).
687            opts: other options to use to parse the input expressions.
688
689        Returns:
690            The new And condition.
691        """
692        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

def or_( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
694    def or_(
695        self,
696        *expressions: t.Optional[ExpOrStr],
697        dialect: DialectType = None,
698        copy: bool = True,
699        **opts,
700    ) -> Condition:
701        """
702        OR this condition with one or multiple expressions.
703
704        Example:
705            >>> condition("x=1").or_("y=1").sql()
706            'x = 1 OR y = 1'
707
708        Args:
709            *expressions: the SQL code strings to parse.
710                If an `Expression` instance is passed, it will be used as-is.
711            dialect: the dialect used to parse the input expression.
712            copy: whether or not to copy the involved expressions (only applies to Expressions).
713            opts: other options to use to parse the input expressions.
714
715        Returns:
716            The new Or condition.
717        """
718        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

def not_(self, copy: bool = True):
720    def not_(self, copy: bool = True):
721        """
722        Wrap this condition with NOT.
723
724        Example:
725            >>> condition("x=1").not_().sql()
726            'NOT x = 1'
727
728        Args:
729            copy: whether or not to copy this object.
730
731        Returns:
732            The new Not instance.
733        """
734        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy: whether or not to copy this object.
Returns:

The new Not instance.

def as_( self, alias: str | sqlglot.expressions.Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Alias:
736    def as_(
737        self,
738        alias: str | Identifier,
739        quoted: t.Optional[bool] = None,
740        dialect: DialectType = None,
741        copy: bool = True,
742        **opts,
743    ) -> Alias:
744        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
761    def isin(
762        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
763    ) -> In:
764        return In(
765            this=_maybe_copy(self, copy),
766            expressions=[convert(e, copy=copy) for e in expressions],
767            query=maybe_parse(query, copy=copy, **opts) if query else None,
768        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> sqlglot.expressions.Between:
770    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
771        return Between(
772            this=_maybe_copy(self, copy),
773            low=convert(low, copy=copy, **opts),
774            high=convert(high, copy=copy, **opts),
775        )
def is_( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Is:
777    def is_(self, other: ExpOrStr) -> Is:
778        return self._binop(Is, other)
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
780    def like(self, other: ExpOrStr) -> Like:
781        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
783    def ilike(self, other: ExpOrStr) -> ILike:
784        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
786    def eq(self, other: t.Any) -> EQ:
787        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
789    def neq(self, other: t.Any) -> NEQ:
790        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
792    def rlike(self, other: ExpOrStr) -> RegexpLike:
793        return self._binop(RegexpLike, other)
key = 'condition'
class Predicate(Condition):
868class Predicate(Condition):
869    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

key = 'predicate'
class DerivedTable(Expression):
872class DerivedTable(Expression):
873    @property
874    def alias_column_names(self) -> t.List[str]:
875        table_alias = self.args.get("alias")
876        if not table_alias:
877            return []
878        return [c.name for c in table_alias.args.get("columns") or []]
879
880    @property
881    def selects(self):
882        return self.this.selects if isinstance(self.this, Subqueryable) else []
883
884    @property
885    def named_selects(self):
886        return [select.output_name for select in self.selects]
alias_column_names: List[str]
selects
named_selects
key = 'derivedtable'
class Unionable(Expression):
889class Unionable(Expression):
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
912
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
935
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union expression.

def intersect( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect expression.

def except_( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except expression.

key = 'unionable'
class UDTF(DerivedTable, Unionable):
960class UDTF(DerivedTable, Unionable):
961    @property
962    def selects(self):
963        alias = self.args.get("alias")
964        return alias.columns if alias else []
selects
key = 'udtf'
class Cache(Expression):
967class Cache(Expression):
968    arg_types = {
969        "with": False,
970        "this": True,
971        "lazy": False,
972        "options": False,
973        "expression": False,
974    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
977class Uncache(Expression):
978    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class Create(Expression):
981class Create(Expression):
982    arg_types = {
983        "with": False,
984        "this": True,
985        "kind": True,
986        "expression": False,
987        "exists": False,
988        "properties": False,
989        "replace": False,
990        "unique": False,
991        "indexes": False,
992        "no_schema_binding": False,
993        "begin": False,
994        "clone": False,
995    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'clone': False}
key = 'create'
class Clone(Expression):
 999class Clone(Expression):
1000    arg_types = {
1001        "this": True,
1002        "when": False,
1003        "kind": False,
1004        "expression": False,
1005    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1008class Describe(Expression):
1009    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1012class Pragma(Expression):
1013    pass
key = 'pragma'
class Set(Expression):
1016class Set(Expression):
1017    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1020class SetItem(Expression):
1021    arg_types = {
1022        "this": False,
1023        "expressions": False,
1024        "kind": False,
1025        "collate": False,  # MySQL SET NAMES statement
1026        "global": False,
1027    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1030class Show(Expression):
1031    arg_types = {
1032        "this": True,
1033        "target": False,
1034        "offset": False,
1035        "limit": False,
1036        "like": False,
1037        "where": False,
1038        "db": False,
1039        "full": False,
1040        "mutex": False,
1041        "query": False,
1042        "channel": False,
1043        "global": False,
1044        "log": False,
1045        "position": False,
1046        "types": False,
1047    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1050class UserDefinedFunction(Expression):
1051    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1054class CharacterSet(Expression):
1055    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1058class With(Expression):
1059    arg_types = {"expressions": True, "recursive": False}
1060
1061    @property
1062    def recursive(self) -> bool:
1063        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1066class WithinGroup(Expression):
1067    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1070class CTE(DerivedTable):
1071    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1074class TableAlias(Expression):
1075    arg_types = {"this": False, "columns": False}
1076
1077    @property
1078    def columns(self):
1079        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1082class BitString(Condition):
1083    pass
key = 'bitstring'
class HexString(Condition):
1086class HexString(Condition):
1087    pass
key = 'hexstring'
class ByteString(Condition):
1090class ByteString(Condition):
1091    pass
key = 'bytestring'
class RawString(Condition):
1094class RawString(Condition):
1095    pass
key = 'rawstring'
class Column(Condition):
1098class Column(Condition):
1099    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1100
1101    @property
1102    def table(self) -> str:
1103        return self.text("table")
1104
1105    @property
1106    def db(self) -> str:
1107        return self.text("db")
1108
1109    @property
1110    def catalog(self) -> str:
1111        return self.text("catalog")
1112
1113    @property
1114    def output_name(self) -> str:
1115        return self.name
1116
1117    @property
1118    def parts(self) -> t.List[Identifier]:
1119        """Return the parts of a column in order catalog, db, table, name."""
1120        return [
1121            t.cast(Identifier, self.args[part])
1122            for part in ("catalog", "db", "table", "this")
1123            if self.args.get(part)
1124        ]
1125
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1139class ColumnPosition(Expression):
1140    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1143class ColumnDef(Expression):
1144    arg_types = {
1145        "this": True,
1146        "kind": False,
1147        "constraints": False,
1148        "exists": False,
1149        "position": False,
1150    }
1151
1152    @property
1153    def constraints(self) -> t.List[ColumnConstraint]:
1154        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1157class AlterColumn(Expression):
1158    arg_types = {
1159        "this": True,
1160        "dtype": False,
1161        "collate": False,
1162        "using": False,
1163        "default": False,
1164        "drop": False,
1165    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1168class RenameTable(Expression):
1169    pass
key = 'renametable'
class Comment(Expression):
1172class Comment(Expression):
1173    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class MergeTreeTTLAction(Expression):
1177class MergeTreeTTLAction(Expression):
1178    arg_types = {
1179        "this": True,
1180        "delete": False,
1181        "recompress": False,
1182        "to_disk": False,
1183        "to_volume": False,
1184    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1188class MergeTreeTTL(Expression):
1189    arg_types = {
1190        "expressions": True,
1191        "where": False,
1192        "group": False,
1193        "aggregates": False,
1194    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class ColumnConstraint(Expression):
1197class ColumnConstraint(Expression):
1198    arg_types = {"this": False, "kind": True}
1199
1200    @property
1201    def kind(self) -> ColumnConstraintKind:
1202        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1205class ColumnConstraintKind(Expression):
1206    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1209class AutoIncrementColumnConstraint(ColumnConstraintKind):
1210    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1213class CaseSpecificColumnConstraint(ColumnConstraintKind):
1214    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1217class CharacterSetColumnConstraint(ColumnConstraintKind):
1218    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1221class CheckColumnConstraint(ColumnConstraintKind):
1222    pass
key = 'checkcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1225class CollateColumnConstraint(ColumnConstraintKind):
1226    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1229class CommentColumnConstraint(ColumnConstraintKind):
1230    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1233class CompressColumnConstraint(ColumnConstraintKind):
1234    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1237class DateFormatColumnConstraint(ColumnConstraintKind):
1238    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1241class DefaultColumnConstraint(ColumnConstraintKind):
1242    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1245class EncodeColumnConstraint(ColumnConstraintKind):
1246    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1249class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1250    # this: True -> ALWAYS, this: False -> BY DEFAULT
1251    arg_types = {
1252        "this": False,
1253        "expression": False,
1254        "on_null": False,
1255        "start": False,
1256        "increment": False,
1257        "minvalue": False,
1258        "maxvalue": False,
1259        "cycle": False,
1260    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1263class InlineLengthColumnConstraint(ColumnConstraintKind):
1264    pass
key = 'inlinelengthcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1267class NotNullColumnConstraint(ColumnConstraintKind):
1268    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1272class OnUpdateColumnConstraint(ColumnConstraintKind):
1273    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1276class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1277    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1280class TitleColumnConstraint(ColumnConstraintKind):
1281    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1284class UniqueColumnConstraint(ColumnConstraintKind):
1285    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1288class UppercaseColumnConstraint(ColumnConstraintKind):
1289    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1292class PathColumnConstraint(ColumnConstraintKind):
1293    pass
key = 'pathcolumnconstraint'
class Constraint(Expression):
1296class Constraint(Expression):
1297    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1300class Delete(Expression):
1301    arg_types = {
1302        "with": False,
1303        "this": False,
1304        "using": False,
1305        "where": False,
1306        "returning": False,
1307        "limit": False,
1308    }
1309
1310    def delete(
1311        self,
1312        table: ExpOrStr,
1313        dialect: DialectType = None,
1314        copy: bool = True,
1315        **opts,
1316    ) -> Delete:
1317        """
1318        Create a DELETE expression or replace the table on an existing DELETE expression.
1319
1320        Example:
1321            >>> delete("tbl").sql()
1322            'DELETE FROM tbl'
1323
1324        Args:
1325            table: the table from which to delete.
1326            dialect: the dialect used to parse the input expression.
1327            copy: if `False`, modify this expression instance in-place.
1328            opts: other options to use to parse the input expressions.
1329
1330        Returns:
1331            Delete: the modified expression.
1332        """
1333        return _apply_builder(
1334            expression=table,
1335            instance=self,
1336            arg="this",
1337            dialect=dialect,
1338            into=Table,
1339            copy=copy,
1340            **opts,
1341        )
1342
1343    def where(
1344        self,
1345        *expressions: t.Optional[ExpOrStr],
1346        append: bool = True,
1347        dialect: DialectType = None,
1348        copy: bool = True,
1349        **opts,
1350    ) -> Delete:
1351        """
1352        Append to or set the WHERE expressions.
1353
1354        Example:
1355            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1356            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1357
1358        Args:
1359            *expressions: the SQL code strings to parse.
1360                If an `Expression` instance is passed, it will be used as-is.
1361                Multiple expressions are combined with an AND operator.
1362            append: if `True`, AND the new expressions to any existing expression.
1363                Otherwise, this resets the expression.
1364            dialect: the dialect used to parse the input expressions.
1365            copy: if `False`, modify this expression instance in-place.
1366            opts: other options to use to parse the input expressions.
1367
1368        Returns:
1369            Delete: the modified expression.
1370        """
1371        return _apply_conjunction_builder(
1372            *expressions,
1373            instance=self,
1374            arg="where",
1375            append=append,
1376            into=Where,
1377            dialect=dialect,
1378            copy=copy,
1379            **opts,
1380        )
1381
1382    def returning(
1383        self,
1384        expression: ExpOrStr,
1385        dialect: DialectType = None,
1386        copy: bool = True,
1387        **opts,
1388    ) -> Delete:
1389        """
1390        Set the RETURNING expression. Not supported by all dialects.
1391
1392        Example:
1393            >>> delete("tbl").returning("*", dialect="postgres").sql()
1394            'DELETE FROM tbl RETURNING *'
1395
1396        Args:
1397            expression: the SQL code strings to parse.
1398                If an `Expression` instance is passed, it will be used as-is.
1399            dialect: the dialect used to parse the input expressions.
1400            copy: if `False`, modify this expression instance in-place.
1401            opts: other options to use to parse the input expressions.
1402
1403        Returns:
1404            Delete: the modified expression.
1405        """
1406        return _apply_builder(
1407            expression=expression,
1408            instance=self,
1409            arg="returning",
1410            prefix="RETURNING",
1411            dialect=dialect,
1412            copy=copy,
1413            into=Returning,
1414            **opts,
1415        )
arg_types = {'with': False, 'this': False, 'using': False, 'where': False, 'returning': False, 'limit': False}
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1310    def delete(
1311        self,
1312        table: ExpOrStr,
1313        dialect: DialectType = None,
1314        copy: bool = True,
1315        **opts,
1316    ) -> Delete:
1317        """
1318        Create a DELETE expression or replace the table on an existing DELETE expression.
1319
1320        Example:
1321            >>> delete("tbl").sql()
1322            'DELETE FROM tbl'
1323
1324        Args:
1325            table: the table from which to delete.
1326            dialect: the dialect used to parse the input expression.
1327            copy: if `False`, modify this expression instance in-place.
1328            opts: other options to use to parse the input expressions.
1329
1330        Returns:
1331            Delete: the modified expression.
1332        """
1333        return _apply_builder(
1334            expression=table,
1335            instance=self,
1336            arg="this",
1337            dialect=dialect,
1338            into=Table,
1339            copy=copy,
1340            **opts,
1341        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1343    def where(
1344        self,
1345        *expressions: t.Optional[ExpOrStr],
1346        append: bool = True,
1347        dialect: DialectType = None,
1348        copy: bool = True,
1349        **opts,
1350    ) -> Delete:
1351        """
1352        Append to or set the WHERE expressions.
1353
1354        Example:
1355            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1356            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1357
1358        Args:
1359            *expressions: the SQL code strings to parse.
1360                If an `Expression` instance is passed, it will be used as-is.
1361                Multiple expressions are combined with an AND operator.
1362            append: if `True`, AND the new expressions to any existing expression.
1363                Otherwise, this resets the expression.
1364            dialect: the dialect used to parse the input expressions.
1365            copy: if `False`, modify this expression instance in-place.
1366            opts: other options to use to parse the input expressions.
1367
1368        Returns:
1369            Delete: the modified expression.
1370        """
1371        return _apply_conjunction_builder(
1372            *expressions,
1373            instance=self,
1374            arg="where",
1375            append=append,
1376            into=Where,
1377            dialect=dialect,
1378            copy=copy,
1379            **opts,
1380        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1382    def returning(
1383        self,
1384        expression: ExpOrStr,
1385        dialect: DialectType = None,
1386        copy: bool = True,
1387        **opts,
1388    ) -> Delete:
1389        """
1390        Set the RETURNING expression. Not supported by all dialects.
1391
1392        Example:
1393            >>> delete("tbl").returning("*", dialect="postgres").sql()
1394            'DELETE FROM tbl RETURNING *'
1395
1396        Args:
1397            expression: the SQL code strings to parse.
1398                If an `Expression` instance is passed, it will be used as-is.
1399            dialect: the dialect used to parse the input expressions.
1400            copy: if `False`, modify this expression instance in-place.
1401            opts: other options to use to parse the input expressions.
1402
1403        Returns:
1404            Delete: the modified expression.
1405        """
1406        return _apply_builder(
1407            expression=expression,
1408            instance=self,
1409            arg="returning",
1410            prefix="RETURNING",
1411            dialect=dialect,
1412            copy=copy,
1413            into=Returning,
1414            **opts,
1415        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

key = 'delete'
class Drop(Expression):
1418class Drop(Expression):
1419    arg_types = {
1420        "this": False,
1421        "kind": False,
1422        "exists": False,
1423        "temporary": False,
1424        "materialized": False,
1425        "cascade": False,
1426        "constraints": False,
1427        "purge": False,
1428    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1431class Filter(Expression):
1432    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1435class Check(Expression):
1436    pass
key = 'check'
class Directory(Expression):
1439class Directory(Expression):
1440    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1441    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1444class ForeignKey(Expression):
1445    arg_types = {
1446        "expressions": True,
1447        "reference": False,
1448        "delete": False,
1449        "update": False,
1450    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1453class PrimaryKey(Expression):
1454    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1459class Into(Expression):
1460    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1463class From(Expression):
1464    @property
1465    def name(self) -> str:
1466        return self.this.name
1467
1468    @property
1469    def alias_or_name(self) -> str:
1470        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1473class Having(Expression):
1474    pass
key = 'having'
class Hint(Expression):
1477class Hint(Expression):
1478    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1481class JoinHint(Expression):
1482    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1485class Identifier(Expression):
1486    arg_types = {"this": True, "quoted": False}
1487
1488    @property
1489    def quoted(self) -> bool:
1490        return bool(self.args.get("quoted"))
1491
1492    @property
1493    def hashable_args(self) -> t.Any:
1494        if self.quoted and any(char.isupper() for char in self.this):
1495            return (self.this, self.quoted)
1496        return self.this.lower()
1497
1498    @property
1499    def output_name(self) -> str:
1500        return self.name
arg_types = {'this': True, 'quoted': False}
quoted: bool
hashable_args: Any
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'identifier'
class Index(Expression):
1503class Index(Expression):
1504    arg_types = {
1505        "this": False,
1506        "table": False,
1507        "using": False,
1508        "where": False,
1509        "columns": False,
1510        "unique": False,
1511        "primary": False,
1512        "amp": False,  # teradata
1513        "partition_by": False,  # teradata
1514    }
arg_types = {'this': False, 'table': False, 'using': False, 'where': False, 'columns': False, 'unique': False, 'primary': False, 'amp': False, 'partition_by': False}
key = 'index'
class Insert(Expression):
1517class Insert(Expression):
1518    arg_types = {
1519        "with": False,
1520        "this": True,
1521        "expression": False,
1522        "conflict": False,
1523        "returning": False,
1524        "overwrite": False,
1525        "exists": False,
1526        "partition": False,
1527        "alternative": False,
1528        "where": False,
1529    }
1530
1531    def with_(
1532        self,
1533        alias: ExpOrStr,
1534        as_: ExpOrStr,
1535        recursive: t.Optional[bool] = None,
1536        append: bool = True,
1537        dialect: DialectType = None,
1538        copy: bool = True,
1539        **opts,
1540    ) -> Insert:
1541        """
1542        Append to or set the common table expressions.
1543
1544        Example:
1545            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1546            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1547
1548        Args:
1549            alias: the SQL code string to parse as the table name.
1550                If an `Expression` instance is passed, this is used as-is.
1551            as_: the SQL code string to parse as the table expression.
1552                If an `Expression` instance is passed, it will be used as-is.
1553            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1554            append: if `True`, add to any existing expressions.
1555                Otherwise, this resets the expressions.
1556            dialect: the dialect used to parse the input expression.
1557            copy: if `False`, modify this expression instance in-place.
1558            opts: other options to use to parse the input expressions.
1559
1560        Returns:
1561            The modified expression.
1562        """
1563        return _apply_cte_builder(
1564            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1565        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': False}
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
1531    def with_(
1532        self,
1533        alias: ExpOrStr,
1534        as_: ExpOrStr,
1535        recursive: t.Optional[bool] = None,
1536        append: bool = True,
1537        dialect: DialectType = None,
1538        copy: bool = True,
1539        **opts,
1540    ) -> Insert:
1541        """
1542        Append to or set the common table expressions.
1543
1544        Example:
1545            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1546            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1547
1548        Args:
1549            alias: the SQL code string to parse as the table name.
1550                If an `Expression` instance is passed, this is used as-is.
1551            as_: the SQL code string to parse as the table expression.
1552                If an `Expression` instance is passed, it will be used as-is.
1553            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1554            append: if `True`, add to any existing expressions.
1555                Otherwise, this resets the expressions.
1556            dialect: the dialect used to parse the input expression.
1557            copy: if `False`, modify this expression instance in-place.
1558            opts: other options to use to parse the input expressions.
1559
1560        Returns:
1561            The modified expression.
1562        """
1563        return _apply_cte_builder(
1564            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1565        )

Append to or set the common table expressions.

Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'insert'
class OnConflict(Expression):
1568class OnConflict(Expression):
1569    arg_types = {
1570        "duplicate": False,
1571        "expressions": False,
1572        "nothing": False,
1573        "key": False,
1574        "constraint": False,
1575    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1578class Returning(Expression):
1579    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'returning'
class Introducer(Expression):
1583class Introducer(Expression):
1584    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1588class National(Expression):
1589    pass
key = 'national'
class LoadData(Expression):
1592class LoadData(Expression):
1593    arg_types = {
1594        "this": True,
1595        "local": False,
1596        "overwrite": False,
1597        "inpath": True,
1598        "partition": False,
1599        "input_format": False,
1600        "serde": False,
1601    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1604class Partition(Expression):
1605    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1608class Fetch(Expression):
1609    arg_types = {
1610        "direction": False,
1611        "count": False,
1612        "percent": False,
1613        "with_ties": False,
1614    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1617class Group(Expression):
1618    arg_types = {
1619        "expressions": False,
1620        "grouping_sets": False,
1621        "cube": False,
1622        "rollup": False,
1623        "totals": False,
1624    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False}
key = 'group'
class Lambda(Expression):
1627class Lambda(Expression):
1628    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1631class Limit(Expression):
1632    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1635class Literal(Condition):
1636    arg_types = {"this": True, "is_string": True}
1637
1638    @property
1639    def hashable_args(self) -> t.Any:
1640        return (self.this, self.args.get("is_string"))
1641
1642    @classmethod
1643    def number(cls, number) -> Literal:
1644        return cls(this=str(number), is_string=False)
1645
1646    @classmethod
1647    def string(cls, string) -> Literal:
1648        return cls(this=str(string), is_string=True)
1649
1650    @property
1651    def output_name(self) -> str:
1652        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1642    @classmethod
1643    def number(cls, number) -> Literal:
1644        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1646    @classmethod
1647    def string(cls, string) -> Literal:
1648        return cls(this=str(string), is_string=True)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1655class Join(Expression):
1656    arg_types = {
1657        "this": True,
1658        "on": False,
1659        "side": False,
1660        "kind": False,
1661        "using": False,
1662        "method": False,
1663        "global": False,
1664        "hint": False,
1665    }
1666
1667    @property
1668    def method(self) -> str:
1669        return self.text("method").upper()
1670
1671    @property
1672    def kind(self) -> str:
1673        return self.text("kind").upper()
1674
1675    @property
1676    def side(self) -> str:
1677        return self.text("side").upper()
1678
1679    @property
1680    def hint(self) -> str:
1681        return self.text("hint").upper()
1682
1683    @property
1684    def alias_or_name(self) -> str:
1685        return self.this.alias_or_name
1686
1687    def on(
1688        self,
1689        *expressions: t.Optional[ExpOrStr],
1690        append: bool = True,
1691        dialect: DialectType = None,
1692        copy: bool = True,
1693        **opts,
1694    ) -> Join:
1695        """
1696        Append to or set the ON expressions.
1697
1698        Example:
1699            >>> import sqlglot
1700            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1701            'JOIN x ON y = 1'
1702
1703        Args:
1704            *expressions: the SQL code strings to parse.
1705                If an `Expression` instance is passed, it will be used as-is.
1706                Multiple expressions are combined with an AND operator.
1707            append: if `True`, AND the new expressions to any existing expression.
1708                Otherwise, this resets the expression.
1709            dialect: the dialect used to parse the input expressions.
1710            copy: if `False`, modify this expression instance in-place.
1711            opts: other options to use to parse the input expressions.
1712
1713        Returns:
1714            The modified Join expression.
1715        """
1716        join = _apply_conjunction_builder(
1717            *expressions,
1718            instance=self,
1719            arg="on",
1720            append=append,
1721            dialect=dialect,
1722            copy=copy,
1723            **opts,
1724        )
1725
1726        if join.kind == "CROSS":
1727            join.set("kind", None)
1728
1729        return join
1730
1731    def using(
1732        self,
1733        *expressions: t.Optional[ExpOrStr],
1734        append: bool = True,
1735        dialect: DialectType = None,
1736        copy: bool = True,
1737        **opts,
1738    ) -> Join:
1739        """
1740        Append to or set the USING expressions.
1741
1742        Example:
1743            >>> import sqlglot
1744            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1745            'JOIN x USING (foo, bla)'
1746
1747        Args:
1748            *expressions: the SQL code strings to parse.
1749                If an `Expression` instance is passed, it will be used as-is.
1750            append: if `True`, concatenate the new expressions to the existing "using" list.
1751                Otherwise, this resets the expression.
1752            dialect: the dialect used to parse the input expressions.
1753            copy: if `False`, modify this expression instance in-place.
1754            opts: other options to use to parse the input expressions.
1755
1756        Returns:
1757            The modified Join expression.
1758        """
1759        join = _apply_list_builder(
1760            *expressions,
1761            instance=self,
1762            arg="using",
1763            append=append,
1764            dialect=dialect,
1765            copy=copy,
1766            **opts,
1767        )
1768
1769        if join.kind == "CROSS":
1770            join.set("kind", None)
1771
1772        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global': False, 'hint': False}
method: str
kind: str
side: str
hint: str
alias_or_name: str
def on( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1687    def on(
1688        self,
1689        *expressions: t.Optional[ExpOrStr],
1690        append: bool = True,
1691        dialect: DialectType = None,
1692        copy: bool = True,
1693        **opts,
1694    ) -> Join:
1695        """
1696        Append to or set the ON expressions.
1697
1698        Example:
1699            >>> import sqlglot
1700            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1701            'JOIN x ON y = 1'
1702
1703        Args:
1704            *expressions: the SQL code strings to parse.
1705                If an `Expression` instance is passed, it will be used as-is.
1706                Multiple expressions are combined with an AND operator.
1707            append: if `True`, AND the new expressions to any existing expression.
1708                Otherwise, this resets the expression.
1709            dialect: the dialect used to parse the input expressions.
1710            copy: if `False`, modify this expression instance in-place.
1711            opts: other options to use to parse the input expressions.
1712
1713        Returns:
1714            The modified Join expression.
1715        """
1716        join = _apply_conjunction_builder(
1717            *expressions,
1718            instance=self,
1719            arg="on",
1720            append=append,
1721            dialect=dialect,
1722            copy=copy,
1723            **opts,
1724        )
1725
1726        if join.kind == "CROSS":
1727            join.set("kind", None)
1728
1729        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1731    def using(
1732        self,
1733        *expressions: t.Optional[ExpOrStr],
1734        append: bool = True,
1735        dialect: DialectType = None,
1736        copy: bool = True,
1737        **opts,
1738    ) -> Join:
1739        """
1740        Append to or set the USING expressions.
1741
1742        Example:
1743            >>> import sqlglot
1744            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1745            'JOIN x USING (foo, bla)'
1746
1747        Args:
1748            *expressions: the SQL code strings to parse.
1749                If an `Expression` instance is passed, it will be used as-is.
1750            append: if `True`, concatenate the new expressions to the existing "using" list.
1751                Otherwise, this resets the expression.
1752            dialect: the dialect used to parse the input expressions.
1753            copy: if `False`, modify this expression instance in-place.
1754            opts: other options to use to parse the input expressions.
1755
1756        Returns:
1757            The modified Join expression.
1758        """
1759        join = _apply_list_builder(
1760            *expressions,
1761            instance=self,
1762            arg="using",
1763            append=append,
1764            dialect=dialect,
1765            copy=copy,
1766            **opts,
1767        )
1768
1769        if join.kind == "CROSS":
1770            join.set("kind", None)
1771
1772        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

key = 'join'
class Lateral(UDTF):
1775class Lateral(UDTF):
1776    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1779class MatchRecognize(Expression):
1780    arg_types = {
1781        "partition_by": False,
1782        "order": False,
1783        "measures": False,
1784        "rows": False,
1785        "after": False,
1786        "pattern": False,
1787        "define": False,
1788        "alias": False,
1789    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1794class Final(Expression):
1795    pass
key = 'final'
class Offset(Expression):
1798class Offset(Expression):
1799    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1802class Order(Expression):
1803    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1808class Cluster(Order):
1809    pass
key = 'cluster'
class Distribute(Order):
1812class Distribute(Order):
1813    pass
key = 'distribute'
class Sort(Order):
1816class Sort(Order):
1817    pass
key = 'sort'
class Ordered(Expression):
1820class Ordered(Expression):
1821    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1824class Property(Expression):
1825    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1828class AlgorithmProperty(Property):
1829    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1832class AutoIncrementProperty(Property):
1833    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1836class BlockCompressionProperty(Property):
1837    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1840class CharacterSetProperty(Property):
1841    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1844class ChecksumProperty(Property):
1845    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1848class CollateProperty(Property):
1849    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1852class CopyGrantsProperty(Property):
1853    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1856class DataBlocksizeProperty(Property):
1857    arg_types = {
1858        "size": False,
1859        "units": False,
1860        "minimum": False,
1861        "maximum": False,
1862        "default": False,
1863    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1866class DefinerProperty(Property):
1867    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1870class DistKeyProperty(Property):
1871    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1874class DistStyleProperty(Property):
1875    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1878class EngineProperty(Property):
1879    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1882class ToTableProperty(Property):
1883    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1886class ExecuteAsProperty(Property):
1887    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1890class ExternalProperty(Property):
1891    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1894class FallbackProperty(Property):
1895    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1898class FileFormatProperty(Property):
1899    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1902class FreespaceProperty(Property):
1903    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1906class InputOutputFormat(Expression):
1907    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1910class IsolatedLoadingProperty(Property):
1911    arg_types = {
1912        "no": True,
1913        "concurrent": True,
1914        "for_all": True,
1915        "for_insert": True,
1916        "for_none": True,
1917    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1920class JournalProperty(Property):
1921    arg_types = {
1922        "no": False,
1923        "dual": False,
1924        "before": False,
1925        "local": False,
1926        "after": False,
1927    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1930class LanguageProperty(Property):
1931    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class DictProperty(Property):
1934class DictProperty(Property):
1935    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1938class DictSubProperty(Property):
1939    pass
key = 'dictsubproperty'
class DictRange(Property):
1942class DictRange(Property):
1943    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1948class OnCluster(Property):
1949    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1952class LikeProperty(Property):
1953    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1956class LocationProperty(Property):
1957    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1960class LockingProperty(Property):
1961    arg_types = {
1962        "this": False,
1963        "kind": True,
1964        "for_or_in": True,
1965        "lock_type": True,
1966        "override": False,
1967    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1970class LogProperty(Property):
1971    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1974class MaterializedProperty(Property):
1975    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1978class MergeBlockRatioProperty(Property):
1979    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
1982class NoPrimaryIndexProperty(Property):
1983    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
1986class OnCommitProperty(Property):
1987    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
1990class PartitionedByProperty(Property):
1991    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
1994class ReturnsProperty(Property):
1995    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
1998class RowFormatProperty(Property):
1999    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2002class RowFormatDelimitedProperty(Property):
2003    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2004    arg_types = {
2005        "fields": False,
2006        "escaped": False,
2007        "collection_items": False,
2008        "map_keys": False,
2009        "lines": False,
2010        "null": False,
2011        "serde": False,
2012    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2015class RowFormatSerdeProperty(Property):
2016    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2019class SchemaCommentProperty(Property):
2020    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2023class SerdeProperties(Property):
2024    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2027class SetProperty(Property):
2028    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2031class SettingsProperty(Property):
2032    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2035class SortKeyProperty(Property):
2036    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2039class SqlSecurityProperty(Property):
2040    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2043class StabilityProperty(Property):
2044    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2047class TemporaryProperty(Property):
2048    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2051class TransientProperty(Property):
2052    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2055class VolatileProperty(Property):
2056    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2059class WithDataProperty(Property):
2060    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2063class WithJournalTableProperty(Property):
2064    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2067class Properties(Expression):
2068    arg_types = {"expressions": True}
2069
2070    NAME_TO_PROPERTY = {
2071        "ALGORITHM": AlgorithmProperty,
2072        "AUTO_INCREMENT": AutoIncrementProperty,
2073        "CHARACTER SET": CharacterSetProperty,
2074        "COLLATE": CollateProperty,
2075        "COMMENT": SchemaCommentProperty,
2076        "DEFINER": DefinerProperty,
2077        "DISTKEY": DistKeyProperty,
2078        "DISTSTYLE": DistStyleProperty,
2079        "ENGINE": EngineProperty,
2080        "EXECUTE AS": ExecuteAsProperty,
2081        "FORMAT": FileFormatProperty,
2082        "LANGUAGE": LanguageProperty,
2083        "LOCATION": LocationProperty,
2084        "PARTITIONED_BY": PartitionedByProperty,
2085        "RETURNS": ReturnsProperty,
2086        "ROW_FORMAT": RowFormatProperty,
2087        "SORTKEY": SortKeyProperty,
2088    }
2089
2090    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2091
2092    # CREATE property locations
2093    # Form: schema specified
2094    #   create [POST_CREATE]
2095    #     table a [POST_NAME]
2096    #     (b int) [POST_SCHEMA]
2097    #     with ([POST_WITH])
2098    #     index (b) [POST_INDEX]
2099    #
2100    # Form: alias selection
2101    #   create [POST_CREATE]
2102    #     table a [POST_NAME]
2103    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2104    #     index (c) [POST_INDEX]
2105    class Location(AutoName):
2106        POST_CREATE = auto()
2107        POST_NAME = auto()
2108        POST_SCHEMA = auto()
2109        POST_WITH = auto()
2110        POST_ALIAS = auto()
2111        POST_EXPRESSION = auto()
2112        POST_INDEX = auto()
2113        UNSUPPORTED = auto()
2114
2115    @classmethod
2116    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2117        expressions = []
2118        for key, value in properties_dict.items():
2119            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2120            if property_cls:
2121                expressions.append(property_cls(this=convert(value)))
2122            else:
2123                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2124
2125        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'sqlglot.expressions.AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'sqlglot.expressions.AutoIncrementProperty'>, 'CHARACTER SET': <class 'sqlglot.expressions.CharacterSetProperty'>, 'COLLATE': <class 'sqlglot.expressions.CollateProperty'>, 'COMMENT': <class 'sqlglot.expressions.SchemaCommentProperty'>, 'DEFINER': <class 'sqlglot.expressions.DefinerProperty'>, 'DISTKEY': <class 'sqlglot.expressions.DistKeyProperty'>, 'DISTSTYLE': <class 'sqlglot.expressions.DistStyleProperty'>, 'ENGINE': <class 'sqlglot.expressions.EngineProperty'>, 'EXECUTE AS': <class 'sqlglot.expressions.ExecuteAsProperty'>, 'FORMAT': <class 'sqlglot.expressions.FileFormatProperty'>, 'LANGUAGE': <class 'sqlglot.expressions.LanguageProperty'>, 'LOCATION': <class 'sqlglot.expressions.LocationProperty'>, 'PARTITIONED_BY': <class 'sqlglot.expressions.PartitionedByProperty'>, 'RETURNS': <class 'sqlglot.expressions.ReturnsProperty'>, 'ROW_FORMAT': <class 'sqlglot.expressions.RowFormatProperty'>, 'SORTKEY': <class 'sqlglot.expressions.SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'sqlglot.expressions.AlgorithmProperty'>: 'ALGORITHM', <class 'sqlglot.expressions.AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'sqlglot.expressions.CharacterSetProperty'>: 'CHARACTER SET', <class 'sqlglot.expressions.CollateProperty'>: 'COLLATE', <class 'sqlglot.expressions.SchemaCommentProperty'>: 'COMMENT', <class 'sqlglot.expressions.DefinerProperty'>: 'DEFINER', <class 'sqlglot.expressions.DistKeyProperty'>: 'DISTKEY', <class 'sqlglot.expressions.DistStyleProperty'>: 'DISTSTYLE', <class 'sqlglot.expressions.EngineProperty'>: 'ENGINE', <class 'sqlglot.expressions.ExecuteAsProperty'>: 'EXECUTE AS', <class 'sqlglot.expressions.FileFormatProperty'>: 'FORMAT', <class 'sqlglot.expressions.LanguageProperty'>: 'LANGUAGE', <class 'sqlglot.expressions.LocationProperty'>: 'LOCATION', <class 'sqlglot.expressions.PartitionedByProperty'>: 'PARTITIONED_BY', <class 'sqlglot.expressions.ReturnsProperty'>: 'RETURNS', <class 'sqlglot.expressions.RowFormatProperty'>: 'ROW_FORMAT', <class 'sqlglot.expressions.SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2115    @classmethod
2116    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2117        expressions = []
2118        for key, value in properties_dict.items():
2119            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2120            if property_cls:
2121                expressions.append(property_cls(this=convert(value)))
2122            else:
2123                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2124
2125        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2105    class Location(AutoName):
2106        POST_CREATE = auto()
2107        POST_NAME = auto()
2108        POST_SCHEMA = auto()
2109        POST_WITH = auto()
2110        POST_ALIAS = auto()
2111        POST_EXPRESSION = auto()
2112        POST_INDEX = auto()
2113        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
2128class Qualify(Expression):
2129    pass
key = 'qualify'
class Return(Expression):
2133class Return(Expression):
2134    pass
key = 'return'
class Reference(Expression):
2137class Reference(Expression):
2138    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2141class Tuple(Expression):
2142    arg_types = {"expressions": False}
2143
2144    def isin(
2145        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2146    ) -> In:
2147        return In(
2148            this=_maybe_copy(self, copy),
2149            expressions=[convert(e, copy=copy) for e in expressions],
2150            query=maybe_parse(query, copy=copy, **opts) if query else None,
2151        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2144    def isin(
2145        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2146    ) -> In:
2147        return In(
2148            this=_maybe_copy(self, copy),
2149            expressions=[convert(e, copy=copy) for e in expressions],
2150            query=maybe_parse(query, copy=copy, **opts) if query else None,
2151        )
key = 'tuple'
class Subqueryable(Unionable):
2154class Subqueryable(Unionable):
2155    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2156        """
2157        Convert this expression to an aliased expression that can be used as a Subquery.
2158
2159        Example:
2160            >>> subquery = Select().select("x").from_("tbl").subquery()
2161            >>> Select().select("x").from_(subquery).sql()
2162            'SELECT x FROM (SELECT x FROM tbl)'
2163
2164        Args:
2165            alias (str | Identifier): an optional alias for the subquery
2166            copy (bool): if `False`, modify this expression instance in-place.
2167
2168        Returns:
2169            Alias: the subquery
2170        """
2171        instance = _maybe_copy(self, copy)
2172        if not isinstance(alias, Expression):
2173            alias = TableAlias(this=to_identifier(alias)) if alias else None
2174
2175        return Subquery(this=instance, alias=alias)
2176
2177    def limit(
2178        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2179    ) -> Select:
2180        raise NotImplementedError
2181
2182    @property
2183    def ctes(self):
2184        with_ = self.args.get("with")
2185        if not with_:
2186            return []
2187        return with_.expressions
2188
2189    @property
2190    def selects(self):
2191        raise NotImplementedError("Subqueryable objects must implement `selects`")
2192
2193    @property
2194    def named_selects(self):
2195        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2196
2197    def with_(
2198        self,
2199        alias: ExpOrStr,
2200        as_: ExpOrStr,
2201        recursive: t.Optional[bool] = None,
2202        append: bool = True,
2203        dialect: DialectType = None,
2204        copy: bool = True,
2205        **opts,
2206    ) -> Subqueryable:
2207        """
2208        Append to or set the common table expressions.
2209
2210        Example:
2211            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2212            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2213
2214        Args:
2215            alias: the SQL code string to parse as the table name.
2216                If an `Expression` instance is passed, this is used as-is.
2217            as_: the SQL code string to parse as the table expression.
2218                If an `Expression` instance is passed, it will be used as-is.
2219            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2220            append: if `True`, add to any existing expressions.
2221                Otherwise, this resets the expressions.
2222            dialect: the dialect used to parse the input expression.
2223            copy: if `False`, modify this expression instance in-place.
2224            opts: other options to use to parse the input expressions.
2225
2226        Returns:
2227            The modified expression.
2228        """
2229        return _apply_cte_builder(
2230            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2231        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2155    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2156        """
2157        Convert this expression to an aliased expression that can be used as a Subquery.
2158
2159        Example:
2160            >>> subquery = Select().select("x").from_("tbl").subquery()
2161            >>> Select().select("x").from_(subquery).sql()
2162            'SELECT x FROM (SELECT x FROM tbl)'
2163
2164        Args:
2165            alias (str | Identifier): an optional alias for the subquery
2166            copy (bool): if `False`, modify this expression instance in-place.
2167
2168        Returns:
2169            Alias: the subquery
2170        """
2171        instance = _maybe_copy(self, copy)
2172        if not isinstance(alias, Expression):
2173            alias = TableAlias(this=to_identifier(alias)) if alias else None
2174
2175        return Subquery(this=instance, alias=alias)

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2177    def limit(
2178        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2179    ) -> Select:
2180        raise NotImplementedError
ctes
selects
named_selects
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Subqueryable:
2197    def with_(
2198        self,
2199        alias: ExpOrStr,
2200        as_: ExpOrStr,
2201        recursive: t.Optional[bool] = None,
2202        append: bool = True,
2203        dialect: DialectType = None,
2204        copy: bool = True,
2205        **opts,
2206    ) -> Subqueryable:
2207        """
2208        Append to or set the common table expressions.
2209
2210        Example:
2211            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2212            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2213
2214        Args:
2215            alias: the SQL code string to parse as the table name.
2216                If an `Expression` instance is passed, this is used as-is.
2217            as_: the SQL code string to parse as the table expression.
2218                If an `Expression` instance is passed, it will be used as-is.
2219            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2220            append: if `True`, add to any existing expressions.
2221                Otherwise, this resets the expressions.
2222            dialect: the dialect used to parse the input expression.
2223            copy: if `False`, modify this expression instance in-place.
2224            opts: other options to use to parse the input expressions.
2225
2226        Returns:
2227            The modified expression.
2228        """
2229        return _apply_cte_builder(
2230            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2231        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'subqueryable'
QUERY_MODIFIERS = {'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
class WithTableHint(Expression):
2258class WithTableHint(Expression):
2259    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2263class IndexTableHint(Expression):
2264    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2267class Table(Expression):
2268    arg_types = {
2269        "this": True,
2270        "alias": False,
2271        "db": False,
2272        "catalog": False,
2273        "laterals": False,
2274        "joins": False,
2275        "pivots": False,
2276        "hints": False,
2277        "system_time": False,
2278    }
2279
2280    @property
2281    def db(self) -> str:
2282        return self.text("db")
2283
2284    @property
2285    def catalog(self) -> str:
2286        return self.text("catalog")
2287
2288    @property
2289    def parts(self) -> t.List[Identifier]:
2290        """Return the parts of a table in order catalog, db, table."""
2291        return [
2292            t.cast(Identifier, self.args[part])
2293            for part in ("catalog", "db", "this")
2294            if self.args.get(part)
2295        ]
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False}
db: str
catalog: str

Return the parts of a table in order catalog, db, table.

key = 'table'
class SystemTime(Expression):
2299class SystemTime(Expression):
2300    arg_types = {
2301        "this": False,
2302        "expression": False,
2303        "kind": True,
2304    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2307class Union(Subqueryable):
2308    arg_types = {
2309        "with": False,
2310        "this": True,
2311        "expression": True,
2312        "distinct": False,
2313        **QUERY_MODIFIERS,
2314    }
2315
2316    def limit(
2317        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2318    ) -> Select:
2319        """
2320        Set the LIMIT expression.
2321
2322        Example:
2323            >>> select("1").union(select("1")).limit(1).sql()
2324            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2325
2326        Args:
2327            expression: the SQL code string to parse.
2328                This can also be an integer.
2329                If a `Limit` instance is passed, this is used as-is.
2330                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2331            dialect: the dialect used to parse the input expression.
2332            copy: if `False`, modify this expression instance in-place.
2333            opts: other options to use to parse the input expressions.
2334
2335        Returns:
2336            The limited subqueryable.
2337        """
2338        return (
2339            select("*")
2340            .from_(self.subquery(alias="_l_0", copy=copy))
2341            .limit(expression, dialect=dialect, copy=False, **opts)
2342        )
2343
2344    def select(
2345        self,
2346        *expressions: t.Optional[ExpOrStr],
2347        append: bool = True,
2348        dialect: DialectType = None,
2349        copy: bool = True,
2350        **opts,
2351    ) -> Union:
2352        """Append to or set the SELECT of the union recursively.
2353
2354        Example:
2355            >>> from sqlglot import parse_one
2356            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2357            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2358
2359        Args:
2360            *expressions: the SQL code strings to parse.
2361                If an `Expression` instance is passed, it will be used as-is.
2362            append: if `True`, add to any existing expressions.
2363                Otherwise, this resets the expressions.
2364            dialect: the dialect used to parse the input expressions.
2365            copy: if `False`, modify this expression instance in-place.
2366            opts: other options to use to parse the input expressions.
2367
2368        Returns:
2369            Union: the modified expression.
2370        """
2371        this = self.copy() if copy else self
2372        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2373        this.expression.unnest().select(
2374            *expressions, append=append, dialect=dialect, copy=False, **opts
2375        )
2376        return this
2377
2378    @property
2379    def named_selects(self):
2380        return self.this.unnest().named_selects
2381
2382    @property
2383    def is_star(self) -> bool:
2384        return self.this.is_star or self.expression.is_star
2385
2386    @property
2387    def selects(self):
2388        return self.this.unnest().selects
2389
2390    @property
2391    def left(self):
2392        return self.this
2393
2394    @property
2395    def right(self):
2396        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2316    def limit(
2317        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2318    ) -> Select:
2319        """
2320        Set the LIMIT expression.
2321
2322        Example:
2323            >>> select("1").union(select("1")).limit(1).sql()
2324            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2325
2326        Args:
2327            expression: the SQL code string to parse.
2328                This can also be an integer.
2329                If a `Limit` instance is passed, this is used as-is.
2330                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2331            dialect: the dialect used to parse the input expression.
2332            copy: if `False`, modify this expression instance in-place.
2333            opts: other options to use to parse the input expressions.
2334
2335        Returns:
2336            The limited subqueryable.
2337        """
2338        return (
2339            select("*")
2340            .from_(self.subquery(alias="_l_0", copy=copy))
2341            .limit(expression, dialect=dialect, copy=False, **opts)
2342        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2344    def select(
2345        self,
2346        *expressions: t.Optional[ExpOrStr],
2347        append: bool = True,
2348        dialect: DialectType = None,
2349        copy: bool = True,
2350        **opts,
2351    ) -> Union:
2352        """Append to or set the SELECT of the union recursively.
2353
2354        Example:
2355            >>> from sqlglot import parse_one
2356            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2357            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2358
2359        Args:
2360            *expressions: the SQL code strings to parse.
2361                If an `Expression` instance is passed, it will be used as-is.
2362            append: if `True`, add to any existing expressions.
2363                Otherwise, this resets the expressions.
2364            dialect: the dialect used to parse the input expressions.
2365            copy: if `False`, modify this expression instance in-place.
2366            opts: other options to use to parse the input expressions.
2367
2368        Returns:
2369            Union: the modified expression.
2370        """
2371        this = self.copy() if copy else self
2372        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2373        this.expression.unnest().select(
2374            *expressions, append=append, dialect=dialect, copy=False, **opts
2375        )
2376        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

named_selects
is_star: bool

Checks whether an expression is a star.

selects
left
right
key = 'union'
class Except(Union):
2399class Except(Union):
2400    pass
key = 'except'
class Intersect(Union):
2403class Intersect(Union):
2404    pass
key = 'intersect'
class Unnest(UDTF):
2407class Unnest(UDTF):
2408    arg_types = {
2409        "expressions": True,
2410        "ordinality": False,
2411        "alias": False,
2412        "offset": False,
2413    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
2416class Update(Expression):
2417    arg_types = {
2418        "with": False,
2419        "this": False,
2420        "expressions": True,
2421        "from": False,
2422        "where": False,
2423        "returning": False,
2424        "limit": False,
2425    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'limit': False}
key = 'update'
class Values(UDTF):
2428class Values(UDTF):
2429    arg_types = {
2430        "expressions": True,
2431        "ordinality": False,
2432        "alias": False,
2433    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2436class Var(Expression):
2437    pass
key = 'var'
class Schema(Expression):
2440class Schema(Expression):
2441    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2446class Lock(Expression):
2447    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
2450class Select(Subqueryable):
2451    arg_types = {
2452        "with": False,
2453        "kind": False,
2454        "expressions": False,
2455        "hint": False,
2456        "distinct": False,
2457        "into": False,
2458        "from": False,
2459        **QUERY_MODIFIERS,
2460    }
2461
2462    def from_(
2463        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2464    ) -> Select:
2465        """
2466        Set the FROM expression.
2467
2468        Example:
2469            >>> Select().from_("tbl").select("x").sql()
2470            'SELECT x FROM tbl'
2471
2472        Args:
2473            expression : the SQL code strings to parse.
2474                If a `From` instance is passed, this is used as-is.
2475                If another `Expression` instance is passed, it will be wrapped in a `From`.
2476            dialect: the dialect used to parse the input expression.
2477            copy: if `False`, modify this expression instance in-place.
2478            opts: other options to use to parse the input expressions.
2479
2480        Returns:
2481            The modified Select expression.
2482        """
2483        return _apply_builder(
2484            expression=expression,
2485            instance=self,
2486            arg="from",
2487            into=From,
2488            prefix="FROM",
2489            dialect=dialect,
2490            copy=copy,
2491            **opts,
2492        )
2493
2494    def group_by(
2495        self,
2496        *expressions: t.Optional[ExpOrStr],
2497        append: bool = True,
2498        dialect: DialectType = None,
2499        copy: bool = True,
2500        **opts,
2501    ) -> Select:
2502        """
2503        Set the GROUP BY expression.
2504
2505        Example:
2506            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2507            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2508
2509        Args:
2510            *expressions: the SQL code strings to parse.
2511                If a `Group` instance is passed, this is used as-is.
2512                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2513                If nothing is passed in then a group by is not applied to the expression
2514            append: if `True`, add to any existing expressions.
2515                Otherwise, this flattens all the `Group` expression into a single expression.
2516            dialect: the dialect used to parse the input expression.
2517            copy: if `False`, modify this expression instance in-place.
2518            opts: other options to use to parse the input expressions.
2519
2520        Returns:
2521            The modified Select expression.
2522        """
2523        if not expressions:
2524            return self if not copy else self.copy()
2525
2526        return _apply_child_list_builder(
2527            *expressions,
2528            instance=self,
2529            arg="group",
2530            append=append,
2531            copy=copy,
2532            prefix="GROUP BY",
2533            into=Group,
2534            dialect=dialect,
2535            **opts,
2536        )
2537
2538    def order_by(
2539        self,
2540        *expressions: t.Optional[ExpOrStr],
2541        append: bool = True,
2542        dialect: DialectType = None,
2543        copy: bool = True,
2544        **opts,
2545    ) -> Select:
2546        """
2547        Set the ORDER BY expression.
2548
2549        Example:
2550            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2551            'SELECT x FROM tbl ORDER BY x DESC'
2552
2553        Args:
2554            *expressions: the SQL code strings to parse.
2555                If a `Group` instance is passed, this is used as-is.
2556                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2557            append: if `True`, add to any existing expressions.
2558                Otherwise, this flattens all the `Order` expression into a single expression.
2559            dialect: the dialect used to parse the input expression.
2560            copy: if `False`, modify this expression instance in-place.
2561            opts: other options to use to parse the input expressions.
2562
2563        Returns:
2564            The modified Select expression.
2565        """
2566        return _apply_child_list_builder(
2567            *expressions,
2568            instance=self,
2569            arg="order",
2570            append=append,
2571            copy=copy,
2572            prefix="ORDER BY",
2573            into=Order,
2574            dialect=dialect,
2575            **opts,
2576        )
2577
2578    def sort_by(
2579        self,
2580        *expressions: t.Optional[ExpOrStr],
2581        append: bool = True,
2582        dialect: DialectType = None,
2583        copy: bool = True,
2584        **opts,
2585    ) -> Select:
2586        """
2587        Set the SORT BY expression.
2588
2589        Example:
2590            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2591            'SELECT x FROM tbl SORT BY x DESC'
2592
2593        Args:
2594            *expressions: the SQL code strings to parse.
2595                If a `Group` instance is passed, this is used as-is.
2596                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2597            append: if `True`, add to any existing expressions.
2598                Otherwise, this flattens all the `Order` expression into a single expression.
2599            dialect: the dialect used to parse the input expression.
2600            copy: if `False`, modify this expression instance in-place.
2601            opts: other options to use to parse the input expressions.
2602
2603        Returns:
2604            The modified Select expression.
2605        """
2606        return _apply_child_list_builder(
2607            *expressions,
2608            instance=self,
2609            arg="sort",
2610            append=append,
2611            copy=copy,
2612            prefix="SORT BY",
2613            into=Sort,
2614            dialect=dialect,
2615            **opts,
2616        )
2617
2618    def cluster_by(
2619        self,
2620        *expressions: t.Optional[ExpOrStr],
2621        append: bool = True,
2622        dialect: DialectType = None,
2623        copy: bool = True,
2624        **opts,
2625    ) -> Select:
2626        """
2627        Set the CLUSTER BY expression.
2628
2629        Example:
2630            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2631            'SELECT x FROM tbl CLUSTER BY x DESC'
2632
2633        Args:
2634            *expressions: the SQL code strings to parse.
2635                If a `Group` instance is passed, this is used as-is.
2636                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2637            append: if `True`, add to any existing expressions.
2638                Otherwise, this flattens all the `Order` expression into a single expression.
2639            dialect: the dialect used to parse the input expression.
2640            copy: if `False`, modify this expression instance in-place.
2641            opts: other options to use to parse the input expressions.
2642
2643        Returns:
2644            The modified Select expression.
2645        """
2646        return _apply_child_list_builder(
2647            *expressions,
2648            instance=self,
2649            arg="cluster",
2650            append=append,
2651            copy=copy,
2652            prefix="CLUSTER BY",
2653            into=Cluster,
2654            dialect=dialect,
2655            **opts,
2656        )
2657
2658    def limit(
2659        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2660    ) -> Select:
2661        """
2662        Set the LIMIT expression.
2663
2664        Example:
2665            >>> Select().from_("tbl").select("x").limit(10).sql()
2666            'SELECT x FROM tbl LIMIT 10'
2667
2668        Args:
2669            expression: the SQL code string to parse.
2670                This can also be an integer.
2671                If a `Limit` instance is passed, this is used as-is.
2672                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2673            dialect: the dialect used to parse the input expression.
2674            copy: if `False`, modify this expression instance in-place.
2675            opts: other options to use to parse the input expressions.
2676
2677        Returns:
2678            Select: the modified expression.
2679        """
2680        return _apply_builder(
2681            expression=expression,
2682            instance=self,
2683            arg="limit",
2684            into=Limit,
2685            prefix="LIMIT",
2686            dialect=dialect,
2687            copy=copy,
2688            **opts,
2689        )
2690
2691    def offset(
2692        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2693    ) -> Select:
2694        """
2695        Set the OFFSET expression.
2696
2697        Example:
2698            >>> Select().from_("tbl").select("x").offset(10).sql()
2699            'SELECT x FROM tbl OFFSET 10'
2700
2701        Args:
2702            expression: the SQL code string to parse.
2703                This can also be an integer.
2704                If a `Offset` instance is passed, this is used as-is.
2705                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2706            dialect: the dialect used to parse the input expression.
2707            copy: if `False`, modify this expression instance in-place.
2708            opts: other options to use to parse the input expressions.
2709
2710        Returns:
2711            The modified Select expression.
2712        """
2713        return _apply_builder(
2714            expression=expression,
2715            instance=self,
2716            arg="offset",
2717            into=Offset,
2718            prefix="OFFSET",
2719            dialect=dialect,
2720            copy=copy,
2721            **opts,
2722        )
2723
2724    def select(
2725        self,
2726        *expressions: t.Optional[ExpOrStr],
2727        append: bool = True,
2728        dialect: DialectType = None,
2729        copy: bool = True,
2730        **opts,
2731    ) -> Select:
2732        """
2733        Append to or set the SELECT expressions.
2734
2735        Example:
2736            >>> Select().select("x", "y").sql()
2737            'SELECT x, y'
2738
2739        Args:
2740            *expressions: the SQL code strings to parse.
2741                If an `Expression` instance is passed, it will be used as-is.
2742            append: if `True`, add to any existing expressions.
2743                Otherwise, this resets the expressions.
2744            dialect: the dialect used to parse the input expressions.
2745            copy: if `False`, modify this expression instance in-place.
2746            opts: other options to use to parse the input expressions.
2747
2748        Returns:
2749            The modified Select expression.
2750        """
2751        return _apply_list_builder(
2752            *expressions,
2753            instance=self,
2754            arg="expressions",
2755            append=append,
2756            dialect=dialect,
2757            copy=copy,
2758            **opts,
2759        )
2760
2761    def lateral(
2762        self,
2763        *expressions: t.Optional[ExpOrStr],
2764        append: bool = True,
2765        dialect: DialectType = None,
2766        copy: bool = True,
2767        **opts,
2768    ) -> Select:
2769        """
2770        Append to or set the LATERAL expressions.
2771
2772        Example:
2773            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2774            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2775
2776        Args:
2777            *expressions: the SQL code strings to parse.
2778                If an `Expression` instance is passed, it will be used as-is.
2779            append: if `True`, add to any existing expressions.
2780                Otherwise, this resets the expressions.
2781            dialect: the dialect used to parse the input expressions.
2782            copy: if `False`, modify this expression instance in-place.
2783            opts: other options to use to parse the input expressions.
2784
2785        Returns:
2786            The modified Select expression.
2787        """
2788        return _apply_list_builder(
2789            *expressions,
2790            instance=self,
2791            arg="laterals",
2792            append=append,
2793            into=Lateral,
2794            prefix="LATERAL VIEW",
2795            dialect=dialect,
2796            copy=copy,
2797            **opts,
2798        )
2799
2800    def join(
2801        self,
2802        expression: ExpOrStr,
2803        on: t.Optional[ExpOrStr] = None,
2804        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2805        append: bool = True,
2806        join_type: t.Optional[str] = None,
2807        join_alias: t.Optional[Identifier | str] = None,
2808        dialect: DialectType = None,
2809        copy: bool = True,
2810        **opts,
2811    ) -> Select:
2812        """
2813        Append to or set the JOIN expressions.
2814
2815        Example:
2816            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2817            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2818
2819            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2820            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2821
2822            Use `join_type` to change the type of join:
2823
2824            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2825            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2826
2827        Args:
2828            expression: the SQL code string to parse.
2829                If an `Expression` instance is passed, it will be used as-is.
2830            on: optionally specify the join "on" criteria as a SQL string.
2831                If an `Expression` instance is passed, it will be used as-is.
2832            using: optionally specify the join "using" criteria as a SQL string.
2833                If an `Expression` instance is passed, it will be used as-is.
2834            append: if `True`, add to any existing expressions.
2835                Otherwise, this resets the expressions.
2836            join_type: if set, alter the parsed join type.
2837            join_alias: an optional alias for the joined source.
2838            dialect: the dialect used to parse the input expressions.
2839            copy: if `False`, modify this expression instance in-place.
2840            opts: other options to use to parse the input expressions.
2841
2842        Returns:
2843            Select: the modified expression.
2844        """
2845        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2846
2847        try:
2848            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2849        except ParseError:
2850            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2851
2852        join = expression if isinstance(expression, Join) else Join(this=expression)
2853
2854        if isinstance(join.this, Select):
2855            join.this.replace(join.this.subquery())
2856
2857        if join_type:
2858            method: t.Optional[Token]
2859            side: t.Optional[Token]
2860            kind: t.Optional[Token]
2861
2862            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2863
2864            if method:
2865                join.set("method", method.text)
2866            if side:
2867                join.set("side", side.text)
2868            if kind:
2869                join.set("kind", kind.text)
2870
2871        if on:
2872            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2873            join.set("on", on)
2874
2875        if using:
2876            join = _apply_list_builder(
2877                *ensure_list(using),
2878                instance=join,
2879                arg="using",
2880                append=append,
2881                copy=copy,
2882                **opts,
2883            )
2884
2885        if join_alias:
2886            join.set("this", alias_(join.this, join_alias, table=True))
2887
2888        return _apply_list_builder(
2889            join,
2890            instance=self,
2891            arg="joins",
2892            append=append,
2893            copy=copy,
2894            **opts,
2895        )
2896
2897    def where(
2898        self,
2899        *expressions: t.Optional[ExpOrStr],
2900        append: bool = True,
2901        dialect: DialectType = None,
2902        copy: bool = True,
2903        **opts,
2904    ) -> Select:
2905        """
2906        Append to or set the WHERE expressions.
2907
2908        Example:
2909            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2910            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2911
2912        Args:
2913            *expressions: the SQL code strings to parse.
2914                If an `Expression` instance is passed, it will be used as-is.
2915                Multiple expressions are combined with an AND operator.
2916            append: if `True`, AND the new expressions to any existing expression.
2917                Otherwise, this resets the expression.
2918            dialect: the dialect used to parse the input expressions.
2919            copy: if `False`, modify this expression instance in-place.
2920            opts: other options to use to parse the input expressions.
2921
2922        Returns:
2923            Select: the modified expression.
2924        """
2925        return _apply_conjunction_builder(
2926            *expressions,
2927            instance=self,
2928            arg="where",
2929            append=append,
2930            into=Where,
2931            dialect=dialect,
2932            copy=copy,
2933            **opts,
2934        )
2935
2936    def having(
2937        self,
2938        *expressions: t.Optional[ExpOrStr],
2939        append: bool = True,
2940        dialect: DialectType = None,
2941        copy: bool = True,
2942        **opts,
2943    ) -> Select:
2944        """
2945        Append to or set the HAVING expressions.
2946
2947        Example:
2948            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2949            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2950
2951        Args:
2952            *expressions: the SQL code strings to parse.
2953                If an `Expression` instance is passed, it will be used as-is.
2954                Multiple expressions are combined with an AND operator.
2955            append: if `True`, AND the new expressions to any existing expression.
2956                Otherwise, this resets the expression.
2957            dialect: the dialect used to parse the input expressions.
2958            copy: if `False`, modify this expression instance in-place.
2959            opts: other options to use to parse the input expressions.
2960
2961        Returns:
2962            The modified Select expression.
2963        """
2964        return _apply_conjunction_builder(
2965            *expressions,
2966            instance=self,
2967            arg="having",
2968            append=append,
2969            into=Having,
2970            dialect=dialect,
2971            copy=copy,
2972            **opts,
2973        )
2974
2975    def window(
2976        self,
2977        *expressions: t.Optional[ExpOrStr],
2978        append: bool = True,
2979        dialect: DialectType = None,
2980        copy: bool = True,
2981        **opts,
2982    ) -> Select:
2983        return _apply_list_builder(
2984            *expressions,
2985            instance=self,
2986            arg="windows",
2987            append=append,
2988            into=Window,
2989            dialect=dialect,
2990            copy=copy,
2991            **opts,
2992        )
2993
2994    def qualify(
2995        self,
2996        *expressions: t.Optional[ExpOrStr],
2997        append: bool = True,
2998        dialect: DialectType = None,
2999        copy: bool = True,
3000        **opts,
3001    ) -> Select:
3002        return _apply_conjunction_builder(
3003            *expressions,
3004            instance=self,
3005            arg="qualify",
3006            append=append,
3007            into=Qualify,
3008            dialect=dialect,
3009            copy=copy,
3010            **opts,
3011        )
3012
3013    def distinct(
3014        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3015    ) -> Select:
3016        """
3017        Set the OFFSET expression.
3018
3019        Example:
3020            >>> Select().from_("tbl").select("x").distinct().sql()
3021            'SELECT DISTINCT x FROM tbl'
3022
3023        Args:
3024            ons: the expressions to distinct on
3025            distinct: whether the Select should be distinct
3026            copy: if `False`, modify this expression instance in-place.
3027
3028        Returns:
3029            Select: the modified expression.
3030        """
3031        instance = _maybe_copy(self, copy)
3032        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3033        instance.set("distinct", Distinct(on=on) if distinct else None)
3034        return instance
3035
3036    def ctas(
3037        self,
3038        table: ExpOrStr,
3039        properties: t.Optional[t.Dict] = None,
3040        dialect: DialectType = None,
3041        copy: bool = True,
3042        **opts,
3043    ) -> Create:
3044        """
3045        Convert this expression to a CREATE TABLE AS statement.
3046
3047        Example:
3048            >>> Select().select("*").from_("tbl").ctas("x").sql()
3049            'CREATE TABLE x AS SELECT * FROM tbl'
3050
3051        Args:
3052            table: the SQL code string to parse as the table name.
3053                If another `Expression` instance is passed, it will be used as-is.
3054            properties: an optional mapping of table properties
3055            dialect: the dialect used to parse the input table.
3056            copy: if `False`, modify this expression instance in-place.
3057            opts: other options to use to parse the input table.
3058
3059        Returns:
3060            The new Create expression.
3061        """
3062        instance = _maybe_copy(self, copy)
3063        table_expression = maybe_parse(
3064            table,
3065            into=Table,
3066            dialect=dialect,
3067            **opts,
3068        )
3069        properties_expression = None
3070        if properties:
3071            properties_expression = Properties.from_dict(properties)
3072
3073        return Create(
3074            this=table_expression,
3075            kind="table",
3076            expression=instance,
3077            properties=properties_expression,
3078        )
3079
3080    def lock(self, update: bool = True, copy: bool = True) -> Select:
3081        """
3082        Set the locking read mode for this expression.
3083
3084        Examples:
3085            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3086            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3087
3088            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3089            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3090
3091        Args:
3092            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3093            copy: if `False`, modify this expression instance in-place.
3094
3095        Returns:
3096            The modified expression.
3097        """
3098        inst = _maybe_copy(self, copy)
3099        inst.set("locks", [Lock(update=update)])
3100
3101        return inst
3102
3103    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3104        """
3105        Set hints for this expression.
3106
3107        Examples:
3108            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3109            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3110
3111        Args:
3112            hints: The SQL code strings to parse as the hints.
3113                If an `Expression` instance is passed, it will be used as-is.
3114            dialect: The dialect used to parse the hints.
3115            copy: If `False`, modify this expression instance in-place.
3116
3117        Returns:
3118            The modified expression.
3119        """
3120        inst = _maybe_copy(self, copy)
3121        inst.set(
3122            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3123        )
3124
3125        return inst
3126
3127    @property
3128    def named_selects(self) -> t.List[str]:
3129        return [e.output_name for e in self.expressions if e.alias_or_name]
3130
3131    @property
3132    def is_star(self) -> bool:
3133        return any(expression.is_star for expression in self.expressions)
3134
3135    @property
3136    def selects(self) -> t.List[Expression]:
3137        return self.expressions
arg_types = {'with': False, 'kind': False, 'expressions': False, 'hint': False, 'distinct': False, 'into': False, 'from': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def from_( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2462    def from_(
2463        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2464    ) -> Select:
2465        """
2466        Set the FROM expression.
2467
2468        Example:
2469            >>> Select().from_("tbl").select("x").sql()
2470            'SELECT x FROM tbl'
2471
2472        Args:
2473            expression : the SQL code strings to parse.
2474                If a `From` instance is passed, this is used as-is.
2475                If another `Expression` instance is passed, it will be wrapped in a `From`.
2476            dialect: the dialect used to parse the input expression.
2477            copy: if `False`, modify this expression instance in-place.
2478            opts: other options to use to parse the input expressions.
2479
2480        Returns:
2481            The modified Select expression.
2482        """
2483        return _apply_builder(
2484            expression=expression,
2485            instance=self,
2486            arg="from",
2487            into=From,
2488            prefix="FROM",
2489            dialect=dialect,
2490            copy=copy,
2491            **opts,
2492        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def group_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2494    def group_by(
2495        self,
2496        *expressions: t.Optional[ExpOrStr],
2497        append: bool = True,
2498        dialect: DialectType = None,
2499        copy: bool = True,
2500        **opts,
2501    ) -> Select:
2502        """
2503        Set the GROUP BY expression.
2504
2505        Example:
2506            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2507            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2508
2509        Args:
2510            *expressions: the SQL code strings to parse.
2511                If a `Group` instance is passed, this is used as-is.
2512                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2513                If nothing is passed in then a group by is not applied to the expression
2514            append: if `True`, add to any existing expressions.
2515                Otherwise, this flattens all the `Group` expression into a single expression.
2516            dialect: the dialect used to parse the input expression.
2517            copy: if `False`, modify this expression instance in-place.
2518            opts: other options to use to parse the input expressions.
2519
2520        Returns:
2521            The modified Select expression.
2522        """
2523        if not expressions:
2524            return self if not copy else self.copy()
2525
2526        return _apply_child_list_builder(
2527            *expressions,
2528            instance=self,
2529            arg="group",
2530            append=append,
2531            copy=copy,
2532            prefix="GROUP BY",
2533            into=Group,
2534            dialect=dialect,
2535            **opts,
2536        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def order_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2538    def order_by(
2539        self,
2540        *expressions: t.Optional[ExpOrStr],
2541        append: bool = True,
2542        dialect: DialectType = None,
2543        copy: bool = True,
2544        **opts,
2545    ) -> Select:
2546        """
2547        Set the ORDER BY expression.
2548
2549        Example:
2550            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2551            'SELECT x FROM tbl ORDER BY x DESC'
2552
2553        Args:
2554            *expressions: the SQL code strings to parse.
2555                If a `Group` instance is passed, this is used as-is.
2556                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2557            append: if `True`, add to any existing expressions.
2558                Otherwise, this flattens all the `Order` expression into a single expression.
2559            dialect: the dialect used to parse the input expression.
2560            copy: if `False`, modify this expression instance in-place.
2561            opts: other options to use to parse the input expressions.
2562
2563        Returns:
2564            The modified Select expression.
2565        """
2566        return _apply_child_list_builder(
2567            *expressions,
2568            instance=self,
2569            arg="order",
2570            append=append,
2571            copy=copy,
2572            prefix="ORDER BY",
2573            into=Order,
2574            dialect=dialect,
2575            **opts,
2576        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def sort_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2578    def sort_by(
2579        self,
2580        *expressions: t.Optional[ExpOrStr],
2581        append: bool = True,
2582        dialect: DialectType = None,
2583        copy: bool = True,
2584        **opts,
2585    ) -> Select:
2586        """
2587        Set the SORT BY expression.
2588
2589        Example:
2590            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2591            'SELECT x FROM tbl SORT BY x DESC'
2592
2593        Args:
2594            *expressions: the SQL code strings to parse.
2595                If a `Group` instance is passed, this is used as-is.
2596                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2597            append: if `True`, add to any existing expressions.
2598                Otherwise, this flattens all the `Order` expression into a single expression.
2599            dialect: the dialect used to parse the input expression.
2600            copy: if `False`, modify this expression instance in-place.
2601            opts: other options to use to parse the input expressions.
2602
2603        Returns:
2604            The modified Select expression.
2605        """
2606        return _apply_child_list_builder(
2607            *expressions,
2608            instance=self,
2609            arg="sort",
2610            append=append,
2611            copy=copy,
2612            prefix="SORT BY",
2613            into=Sort,
2614            dialect=dialect,
2615            **opts,
2616        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def cluster_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2618    def cluster_by(
2619        self,
2620        *expressions: t.Optional[ExpOrStr],
2621        append: bool = True,
2622        dialect: DialectType = None,
2623        copy: bool = True,
2624        **opts,
2625    ) -> Select:
2626        """
2627        Set the CLUSTER BY expression.
2628
2629        Example:
2630            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2631            'SELECT x FROM tbl CLUSTER BY x DESC'
2632
2633        Args:
2634            *expressions: the SQL code strings to parse.
2635                If a `Group` instance is passed, this is used as-is.
2636                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2637            append: if `True`, add to any existing expressions.
2638                Otherwise, this flattens all the `Order` expression into a single expression.
2639            dialect: the dialect used to parse the input expression.
2640            copy: if `False`, modify this expression instance in-place.
2641            opts: other options to use to parse the input expressions.
2642
2643        Returns:
2644            The modified Select expression.
2645        """
2646        return _apply_child_list_builder(
2647            *expressions,
2648            instance=self,
2649            arg="cluster",
2650            append=append,
2651            copy=copy,
2652            prefix="CLUSTER BY",
2653            into=Cluster,
2654            dialect=dialect,
2655            **opts,
2656        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2658    def limit(
2659        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2660    ) -> Select:
2661        """
2662        Set the LIMIT expression.
2663
2664        Example:
2665            >>> Select().from_("tbl").select("x").limit(10).sql()
2666            'SELECT x FROM tbl LIMIT 10'
2667
2668        Args:
2669            expression: the SQL code string to parse.
2670                This can also be an integer.
2671                If a `Limit` instance is passed, this is used as-is.
2672                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2673            dialect: the dialect used to parse the input expression.
2674            copy: if `False`, modify this expression instance in-place.
2675            opts: other options to use to parse the input expressions.
2676
2677        Returns:
2678            Select: the modified expression.
2679        """
2680        return _apply_builder(
2681            expression=expression,
2682            instance=self,
2683            arg="limit",
2684            into=Limit,
2685            prefix="LIMIT",
2686            dialect=dialect,
2687            copy=copy,
2688            **opts,
2689        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2691    def offset(
2692        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2693    ) -> Select:
2694        """
2695        Set the OFFSET expression.
2696
2697        Example:
2698            >>> Select().from_("tbl").select("x").offset(10).sql()
2699            'SELECT x FROM tbl OFFSET 10'
2700
2701        Args:
2702            expression: the SQL code string to parse.
2703                This can also be an integer.
2704                If a `Offset` instance is passed, this is used as-is.
2705                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2706            dialect: the dialect used to parse the input expression.
2707            copy: if `False`, modify this expression instance in-place.
2708            opts: other options to use to parse the input expressions.
2709
2710        Returns:
2711            The modified Select expression.
2712        """
2713        return _apply_builder(
2714            expression=expression,
2715            instance=self,
2716            arg="offset",
2717            into=Offset,
2718            prefix="OFFSET",
2719            dialect=dialect,
2720            copy=copy,
2721            **opts,
2722        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2724    def select(
2725        self,
2726        *expressions: t.Optional[ExpOrStr],
2727        append: bool = True,
2728        dialect: DialectType = None,
2729        copy: bool = True,
2730        **opts,
2731    ) -> Select:
2732        """
2733        Append to or set the SELECT expressions.
2734
2735        Example:
2736            >>> Select().select("x", "y").sql()
2737            'SELECT x, y'
2738
2739        Args:
2740            *expressions: the SQL code strings to parse.
2741                If an `Expression` instance is passed, it will be used as-is.
2742            append: if `True`, add to any existing expressions.
2743                Otherwise, this resets the expressions.
2744            dialect: the dialect used to parse the input expressions.
2745            copy: if `False`, modify this expression instance in-place.
2746            opts: other options to use to parse the input expressions.
2747
2748        Returns:
2749            The modified Select expression.
2750        """
2751        return _apply_list_builder(
2752            *expressions,
2753            instance=self,
2754            arg="expressions",
2755            append=append,
2756            dialect=dialect,
2757            copy=copy,
2758            **opts,
2759        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def lateral( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2761    def lateral(
2762        self,
2763        *expressions: t.Optional[ExpOrStr],
2764        append: bool = True,
2765        dialect: DialectType = None,
2766        copy: bool = True,
2767        **opts,
2768    ) -> Select:
2769        """
2770        Append to or set the LATERAL expressions.
2771
2772        Example:
2773            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2774            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2775
2776        Args:
2777            *expressions: the SQL code strings to parse.
2778                If an `Expression` instance is passed, it will be used as-is.
2779            append: if `True`, add to any existing expressions.
2780                Otherwise, this resets the expressions.
2781            dialect: the dialect used to parse the input expressions.
2782            copy: if `False`, modify this expression instance in-place.
2783            opts: other options to use to parse the input expressions.
2784
2785        Returns:
2786            The modified Select expression.
2787        """
2788        return _apply_list_builder(
2789            *expressions,
2790            instance=self,
2791            arg="laterals",
2792            append=append,
2793            into=Lateral,
2794            prefix="LATERAL VIEW",
2795            dialect=dialect,
2796            copy=copy,
2797            **opts,
2798        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def join( self, expression: Union[str, sqlglot.expressions.Expression], on: Union[str, sqlglot.expressions.Expression, NoneType] = None, using: Union[str, sqlglot.expressions.Expression, List[Union[str, sqlglot.expressions.Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2800    def join(
2801        self,
2802        expression: ExpOrStr,
2803        on: t.Optional[ExpOrStr] = None,
2804        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2805        append: bool = True,
2806        join_type: t.Optional[str] = None,
2807        join_alias: t.Optional[Identifier | str] = None,
2808        dialect: DialectType = None,
2809        copy: bool = True,
2810        **opts,
2811    ) -> Select:
2812        """
2813        Append to or set the JOIN expressions.
2814
2815        Example:
2816            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2817            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2818
2819            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2820            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2821
2822            Use `join_type` to change the type of join:
2823
2824            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2825            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2826
2827        Args:
2828            expression: the SQL code string to parse.
2829                If an `Expression` instance is passed, it will be used as-is.
2830            on: optionally specify the join "on" criteria as a SQL string.
2831                If an `Expression` instance is passed, it will be used as-is.
2832            using: optionally specify the join "using" criteria as a SQL string.
2833                If an `Expression` instance is passed, it will be used as-is.
2834            append: if `True`, add to any existing expressions.
2835                Otherwise, this resets the expressions.
2836            join_type: if set, alter the parsed join type.
2837            join_alias: an optional alias for the joined source.
2838            dialect: the dialect used to parse the input expressions.
2839            copy: if `False`, modify this expression instance in-place.
2840            opts: other options to use to parse the input expressions.
2841
2842        Returns:
2843            Select: the modified expression.
2844        """
2845        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2846
2847        try:
2848            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2849        except ParseError:
2850            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2851
2852        join = expression if isinstance(expression, Join) else Join(this=expression)
2853
2854        if isinstance(join.this, Select):
2855            join.this.replace(join.this.subquery())
2856
2857        if join_type:
2858            method: t.Optional[Token]
2859            side: t.Optional[Token]
2860            kind: t.Optional[Token]
2861
2862            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2863
2864            if method:
2865                join.set("method", method.text)
2866            if side:
2867                join.set("side", side.text)
2868            if kind:
2869                join.set("kind", kind.text)
2870
2871        if on:
2872            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2873            join.set("on", on)
2874
2875        if using:
2876            join = _apply_list_builder(
2877                *ensure_list(using),
2878                instance=join,
2879                arg="using",
2880                append=append,
2881                copy=copy,
2882                **opts,
2883            )
2884
2885        if join_alias:
2886            join.set("this", alias_(join.this, join_alias, table=True))
2887
2888        return _apply_list_builder(
2889            join,
2890            instance=self,
2891            arg="joins",
2892            append=append,
2893            copy=copy,
2894            **opts,
2895        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on: optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using: optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type: if set, alter the parsed join type.
  • join_alias: an optional alias for the joined source.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2897    def where(
2898        self,
2899        *expressions: t.Optional[ExpOrStr],
2900        append: bool = True,
2901        dialect: DialectType = None,
2902        copy: bool = True,
2903        **opts,
2904    ) -> Select:
2905        """
2906        Append to or set the WHERE expressions.
2907
2908        Example:
2909            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2910            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2911
2912        Args:
2913            *expressions: the SQL code strings to parse.
2914                If an `Expression` instance is passed, it will be used as-is.
2915                Multiple expressions are combined with an AND operator.
2916            append: if `True`, AND the new expressions to any existing expression.
2917                Otherwise, this resets the expression.
2918            dialect: the dialect used to parse the input expressions.
2919            copy: if `False`, modify this expression instance in-place.
2920            opts: other options to use to parse the input expressions.
2921
2922        Returns:
2923            Select: the modified expression.
2924        """
2925        return _apply_conjunction_builder(
2926            *expressions,
2927            instance=self,
2928            arg="where",
2929            append=append,
2930            into=Where,
2931            dialect=dialect,
2932            copy=copy,
2933            **opts,
2934        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2936    def having(
2937        self,
2938        *expressions: t.Optional[ExpOrStr],
2939        append: bool = True,
2940        dialect: DialectType = None,
2941        copy: bool = True,
2942        **opts,
2943    ) -> Select:
2944        """
2945        Append to or set the HAVING expressions.
2946
2947        Example:
2948            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2949            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2950
2951        Args:
2952            *expressions: the SQL code strings to parse.
2953                If an `Expression` instance is passed, it will be used as-is.
2954                Multiple expressions are combined with an AND operator.
2955            append: if `True`, AND the new expressions to any existing expression.
2956                Otherwise, this resets the expression.
2957            dialect: the dialect used to parse the input expressions.
2958            copy: if `False`, modify this expression instance in-place.
2959            opts: other options to use to parse the input expressions.
2960
2961        Returns:
2962            The modified Select expression.
2963        """
2964        return _apply_conjunction_builder(
2965            *expressions,
2966            instance=self,
2967            arg="having",
2968            append=append,
2969            into=Having,
2970            dialect=dialect,
2971            copy=copy,
2972            **opts,
2973        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def window( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2975    def window(
2976        self,
2977        *expressions: t.Optional[ExpOrStr],
2978        append: bool = True,
2979        dialect: DialectType = None,
2980        copy: bool = True,
2981        **opts,
2982    ) -> Select:
2983        return _apply_list_builder(
2984            *expressions,
2985            instance=self,
2986            arg="windows",
2987            append=append,
2988            into=Window,
2989            dialect=dialect,
2990            copy=copy,
2991            **opts,
2992        )
def qualify( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2994    def qualify(
2995        self,
2996        *expressions: t.Optional[ExpOrStr],
2997        append: bool = True,
2998        dialect: DialectType = None,
2999        copy: bool = True,
3000        **opts,
3001    ) -> Select:
3002        return _apply_conjunction_builder(
3003            *expressions,
3004            instance=self,
3005            arg="qualify",
3006            append=append,
3007            into=Qualify,
3008            dialect=dialect,
3009            copy=copy,
3010            **opts,
3011        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3013    def distinct(
3014        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3015    ) -> Select:
3016        """
3017        Set the OFFSET expression.
3018
3019        Example:
3020            >>> Select().from_("tbl").select("x").distinct().sql()
3021            'SELECT DISTINCT x FROM tbl'
3022
3023        Args:
3024            ons: the expressions to distinct on
3025            distinct: whether the Select should be distinct
3026            copy: if `False`, modify this expression instance in-place.
3027
3028        Returns:
3029            Select: the modified expression.
3030        """
3031        instance = _maybe_copy(self, copy)
3032        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3033        instance.set("distinct", Distinct(on=on) if distinct else None)
3034        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table: Union[str, sqlglot.expressions.Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Create:
3036    def ctas(
3037        self,
3038        table: ExpOrStr,
3039        properties: t.Optional[t.Dict] = None,
3040        dialect: DialectType = None,
3041        copy: bool = True,
3042        **opts,
3043    ) -> Create:
3044        """
3045        Convert this expression to a CREATE TABLE AS statement.
3046
3047        Example:
3048            >>> Select().select("*").from_("tbl").ctas("x").sql()
3049            'CREATE TABLE x AS SELECT * FROM tbl'
3050
3051        Args:
3052            table: the SQL code string to parse as the table name.
3053                If another `Expression` instance is passed, it will be used as-is.
3054            properties: an optional mapping of table properties
3055            dialect: the dialect used to parse the input table.
3056            copy: if `False`, modify this expression instance in-place.
3057            opts: other options to use to parse the input table.
3058
3059        Returns:
3060            The new Create expression.
3061        """
3062        instance = _maybe_copy(self, copy)
3063        table_expression = maybe_parse(
3064            table,
3065            into=Table,
3066            dialect=dialect,
3067            **opts,
3068        )
3069        properties_expression = None
3070        if properties:
3071            properties_expression = Properties.from_dict(properties)
3072
3073        return Create(
3074            this=table_expression,
3075            kind="table",
3076            expression=instance,
3077            properties=properties_expression,
3078        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table: the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties: an optional mapping of table properties
  • dialect: the dialect used to parse the input table.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input table.
Returns:

The new Create expression.

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3080    def lock(self, update: bool = True, copy: bool = True) -> Select:
3081        """
3082        Set the locking read mode for this expression.
3083
3084        Examples:
3085            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3086            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3087
3088            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3089            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3090
3091        Args:
3092            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3093            copy: if `False`, modify this expression instance in-place.
3094
3095        Returns:
3096            The modified expression.
3097        """
3098        inst = _maybe_copy(self, copy)
3099        inst.set("locks", [Lock(update=update)])
3100
3101        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

def hint( self, *hints: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> sqlglot.expressions.Select:
3103    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3104        """
3105        Set hints for this expression.
3106
3107        Examples:
3108            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3109            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3110
3111        Args:
3112            hints: The SQL code strings to parse as the hints.
3113                If an `Expression` instance is passed, it will be used as-is.
3114            dialect: The dialect used to parse the hints.
3115            copy: If `False`, modify this expression instance in-place.
3116
3117        Returns:
3118            The modified expression.
3119        """
3120        inst = _maybe_copy(self, copy)
3121        inst.set(
3122            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3123        )
3124
3125        return inst

Set hints for this expression.

Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
  • hints: The SQL code strings to parse as the hints. If an Expression instance is passed, it will be used as-is.
  • dialect: The dialect used to parse the hints.
  • copy: If False, modify this expression instance in-place.
Returns:

The modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

key = 'select'
class Subquery(DerivedTable, Unionable):
3140class Subquery(DerivedTable, Unionable):
3141    arg_types = {
3142        "this": True,
3143        "alias": False,
3144        "with": False,
3145        **QUERY_MODIFIERS,
3146    }
3147
3148    def unnest(self):
3149        """
3150        Returns the first non subquery.
3151        """
3152        expression = self
3153        while isinstance(expression, Subquery):
3154            expression = expression.this
3155        return expression
3156
3157    @property
3158    def is_star(self) -> bool:
3159        return self.this.is_star
3160
3161    @property
3162    def output_name(self) -> str:
3163        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def unnest(self):
3148    def unnest(self):
3149        """
3150        Returns the first non subquery.
3151        """
3152        expression = self
3153        while isinstance(expression, Subquery):
3154            expression = expression.this
3155        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3166class TableSample(Expression):
3167    arg_types = {
3168        "this": False,
3169        "method": False,
3170        "bucket_numerator": False,
3171        "bucket_denominator": False,
3172        "bucket_field": False,
3173        "percent": False,
3174        "rows": False,
3175        "size": False,
3176        "seed": False,
3177        "kind": False,
3178    }
arg_types = {'this': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False, 'kind': False}
key = 'tablesample'
class Tag(Expression):
3181class Tag(Expression):
3182    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3183
3184    arg_types = {
3185        "this": False,
3186        "prefix": False,
3187        "postfix": False,
3188    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3193class Pivot(Expression):
3194    arg_types = {
3195        "this": False,
3196        "alias": False,
3197        "expressions": True,
3198        "field": False,
3199        "unpivot": False,
3200        "using": False,
3201        "group": False,
3202        "columns": False,
3203    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3206class Window(Expression):
3207    arg_types = {
3208        "this": True,
3209        "partition_by": False,
3210        "order": False,
3211        "spec": False,
3212        "alias": False,
3213        "over": False,
3214        "first": False,
3215    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3218class WindowSpec(Expression):
3219    arg_types = {
3220        "kind": False,
3221        "start": False,
3222        "start_side": False,
3223        "end": False,
3224        "end_side": False,
3225    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3228class Where(Expression):
3229    pass
key = 'where'
class Star(Expression):
3232class Star(Expression):
3233    arg_types = {"except": False, "replace": False}
3234
3235    @property
3236    def name(self) -> str:
3237        return "*"
3238
3239    @property
3240    def output_name(self) -> str:
3241        return self.name
arg_types = {'except': False, 'replace': False}
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'star'
class Parameter(Condition):
3244class Parameter(Condition):
3245    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3248class SessionParameter(Condition):
3249    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3252class Placeholder(Condition):
3253    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3256class Null(Condition):
3257    arg_types: t.Dict[str, t.Any] = {}
3258
3259    @property
3260    def name(self) -> str:
3261        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3264class Boolean(Condition):
3265    pass
key = 'boolean'
class DataTypeSize(Expression):
3268class DataTypeSize(Expression):
3269    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3272class DataType(Expression):
3273    arg_types = {
3274        "this": True,
3275        "expressions": False,
3276        "nested": False,
3277        "values": False,
3278        "prefix": False,
3279    }
3280
3281    class Type(AutoName):
3282        ARRAY = auto()
3283        BIGDECIMAL = auto()
3284        BIGINT = auto()
3285        BIGSERIAL = auto()
3286        BINARY = auto()
3287        BIT = auto()
3288        BOOLEAN = auto()
3289        CHAR = auto()
3290        DATE = auto()
3291        DATETIME = auto()
3292        DATETIME64 = auto()
3293        ENUM = auto()
3294        INT4RANGE = auto()
3295        INT4MULTIRANGE = auto()
3296        INT8RANGE = auto()
3297        INT8MULTIRANGE = auto()
3298        NUMRANGE = auto()
3299        NUMMULTIRANGE = auto()
3300        TSRANGE = auto()
3301        TSMULTIRANGE = auto()
3302        TSTZRANGE = auto()
3303        TSTZMULTIRANGE = auto()
3304        DATERANGE = auto()
3305        DATEMULTIRANGE = auto()
3306        DECIMAL = auto()
3307        DOUBLE = auto()
3308        FLOAT = auto()
3309        GEOGRAPHY = auto()
3310        GEOMETRY = auto()
3311        HLLSKETCH = auto()
3312        HSTORE = auto()
3313        IMAGE = auto()
3314        INET = auto()
3315        INT = auto()
3316        INT128 = auto()
3317        INT256 = auto()
3318        INTERVAL = auto()
3319        JSON = auto()
3320        JSONB = auto()
3321        LONGBLOB = auto()
3322        LONGTEXT = auto()
3323        MAP = auto()
3324        MEDIUMBLOB = auto()
3325        MEDIUMTEXT = auto()
3326        MONEY = auto()
3327        NCHAR = auto()
3328        NULL = auto()
3329        NULLABLE = auto()
3330        NVARCHAR = auto()
3331        OBJECT = auto()
3332        ROWVERSION = auto()
3333        SERIAL = auto()
3334        SET = auto()
3335        SMALLINT = auto()
3336        SMALLMONEY = auto()
3337        SMALLSERIAL = auto()
3338        STRUCT = auto()
3339        SUPER = auto()
3340        TEXT = auto()
3341        TIME = auto()
3342        TIMESTAMP = auto()
3343        TIMESTAMPTZ = auto()
3344        TIMESTAMPLTZ = auto()
3345        TINYINT = auto()
3346        UBIGINT = auto()
3347        UINT = auto()
3348        USMALLINT = auto()
3349        UTINYINT = auto()
3350        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3351        UINT128 = auto()
3352        UINT256 = auto()
3353        UNIQUEIDENTIFIER = auto()
3354        USERDEFINED = "USER-DEFINED"
3355        UUID = auto()
3356        VARBINARY = auto()
3357        VARCHAR = auto()
3358        VARIANT = auto()
3359        XML = auto()
3360
3361    TEXT_TYPES = {
3362        Type.CHAR,
3363        Type.NCHAR,
3364        Type.VARCHAR,
3365        Type.NVARCHAR,
3366        Type.TEXT,
3367    }
3368
3369    INTEGER_TYPES = {
3370        Type.INT,
3371        Type.TINYINT,
3372        Type.SMALLINT,
3373        Type.BIGINT,
3374        Type.INT128,
3375        Type.INT256,
3376    }
3377
3378    FLOAT_TYPES = {
3379        Type.FLOAT,
3380        Type.DOUBLE,
3381    }
3382
3383    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3384
3385    TEMPORAL_TYPES = {
3386        Type.TIME,
3387        Type.TIMESTAMP,
3388        Type.TIMESTAMPTZ,
3389        Type.TIMESTAMPLTZ,
3390        Type.DATE,
3391        Type.DATETIME,
3392        Type.DATETIME64,
3393    }
3394
3395    META_TYPES = {"UNKNOWN", "NULL"}
3396
3397    @classmethod
3398    def build(
3399        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3400    ) -> DataType:
3401        from sqlglot import parse_one
3402
3403        if isinstance(dtype, str):
3404            upper = dtype.upper()
3405            if upper in DataType.META_TYPES:
3406                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3407            else:
3408                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3409
3410            if data_type_exp is None:
3411                raise ValueError(f"Unparsable data type value: {dtype}")
3412        elif isinstance(dtype, DataType.Type):
3413            data_type_exp = DataType(this=dtype)
3414        elif isinstance(dtype, DataType):
3415            return dtype
3416        else:
3417            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3418
3419        return DataType(**{**data_type_exp.args, **kwargs})
3420
3421    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3422        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.TEXT: 'TEXT'>}
INTEGER_TYPES = {<Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT256: 'INT256'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.BIGINT: 'BIGINT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.INT: 'INT'>, <Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT256: 'INT256'>, <Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>}
TEMPORAL_TYPES = {<Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIME: 'TIME'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.DATE: 'DATE'>}
META_TYPES = {'NULL', 'UNKNOWN'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3397    @classmethod
3398    def build(
3399        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3400    ) -> DataType:
3401        from sqlglot import parse_one
3402
3403        if isinstance(dtype, str):
3404            upper = dtype.upper()
3405            if upper in DataType.META_TYPES:
3406                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3407            else:
3408                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3409
3410            if data_type_exp is None:
3411                raise ValueError(f"Unparsable data type value: {dtype}")
3412        elif isinstance(dtype, DataType.Type):
3413            data_type_exp = DataType(this=dtype)
3414        elif isinstance(dtype, DataType):
3415            return dtype
3416        else:
3417            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3418
3419        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3421    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3422        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3281    class Type(AutoName):
3282        ARRAY = auto()
3283        BIGDECIMAL = auto()
3284        BIGINT = auto()
3285        BIGSERIAL = auto()
3286        BINARY = auto()
3287        BIT = auto()
3288        BOOLEAN = auto()
3289        CHAR = auto()
3290        DATE = auto()
3291        DATETIME = auto()
3292        DATETIME64 = auto()
3293        ENUM = auto()
3294        INT4RANGE = auto()
3295        INT4MULTIRANGE = auto()
3296        INT8RANGE = auto()
3297        INT8MULTIRANGE = auto()
3298        NUMRANGE = auto()
3299        NUMMULTIRANGE = auto()
3300        TSRANGE = auto()
3301        TSMULTIRANGE = auto()
3302        TSTZRANGE = auto()
3303        TSTZMULTIRANGE = auto()
3304        DATERANGE = auto()
3305        DATEMULTIRANGE = auto()
3306        DECIMAL = auto()
3307        DOUBLE = auto()
3308        FLOAT = auto()
3309        GEOGRAPHY = auto()
3310        GEOMETRY = auto()
3311        HLLSKETCH = auto()
3312        HSTORE = auto()
3313        IMAGE = auto()
3314        INET = auto()
3315        INT = auto()
3316        INT128 = auto()
3317        INT256 = auto()
3318        INTERVAL = auto()
3319        JSON = auto()
3320        JSONB = auto()
3321        LONGBLOB = auto()
3322        LONGTEXT = auto()
3323        MAP = auto()
3324        MEDIUMBLOB = auto()
3325        MEDIUMTEXT = auto()
3326        MONEY = auto()
3327        NCHAR = auto()
3328        NULL = auto()
3329        NULLABLE = auto()
3330        NVARCHAR = auto()
3331        OBJECT = auto()
3332        ROWVERSION = auto()
3333        SERIAL = auto()
3334        SET = auto()
3335        SMALLINT = auto()
3336        SMALLMONEY = auto()
3337        SMALLSERIAL = auto()
3338        STRUCT = auto()
3339        SUPER = auto()
3340        TEXT = auto()
3341        TIME = auto()
3342        TIMESTAMP = auto()
3343        TIMESTAMPTZ = auto()
3344        TIMESTAMPLTZ = auto()
3345        TINYINT = auto()
3346        UBIGINT = auto()
3347        UINT = auto()
3348        USMALLINT = auto()
3349        UTINYINT = auto()
3350        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3351        UINT128 = auto()
3352        UINT256 = auto()
3353        UNIQUEIDENTIFIER = auto()
3354        USERDEFINED = "USER-DEFINED"
3355        UUID = auto()
3356        VARBINARY = auto()
3357        VARCHAR = auto()
3358        VARIANT = auto()
3359        XML = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ENUM = <Type.ENUM: 'ENUM'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3426class PseudoType(Expression):
3427    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3431class SubqueryPredicate(Predicate):
3432    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3435class All(SubqueryPredicate):
3436    pass
key = 'all'
class Any(SubqueryPredicate):
3439class Any(SubqueryPredicate):
3440    pass
key = 'any'
class Exists(SubqueryPredicate):
3443class Exists(SubqueryPredicate):
3444    pass
key = 'exists'
class Command(Expression):
3449class Command(Expression):
3450    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3453class Transaction(Expression):
3454    arg_types = {"this": False, "modes": False}
arg_types = {'this': False, 'modes': False}
key = 'transaction'
class Commit(Expression):
3457class Commit(Expression):
3458    arg_types = {"chain": False}
arg_types = {'chain': False}
key = 'commit'
class Rollback(Expression):
3461class Rollback(Expression):
3462    arg_types = {"savepoint": False}
arg_types = {'savepoint': False}
key = 'rollback'
class AlterTable(Expression):
3465class AlterTable(Expression):
3466    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3469class AddConstraint(Expression):
3470    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3473class DropPartition(Expression):
3474    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3478class Binary(Condition):
3479    arg_types = {"this": True, "expression": True}
3480
3481    @property
3482    def left(self):
3483        return self.this
3484
3485    @property
3486    def right(self):
3487        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3490class Add(Binary):
3491    pass
key = 'add'
class Connector(Binary):
3494class Connector(Binary):
3495    pass
key = 'connector'
class And(Connector):
3498class And(Connector):
3499    pass
key = 'and'
class Or(Connector):
3502class Or(Connector):
3503    pass
key = 'or'
class BitwiseAnd(Binary):
3506class BitwiseAnd(Binary):
3507    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3510class BitwiseLeftShift(Binary):
3511    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3514class BitwiseOr(Binary):
3515    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3518class BitwiseRightShift(Binary):
3519    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3522class BitwiseXor(Binary):
3523    pass
key = 'bitwisexor'
class Div(Binary):
3526class Div(Binary):
3527    pass
key = 'div'
class Overlaps(Binary):
3530class Overlaps(Binary):
3531    pass
key = 'overlaps'
class Dot(Binary):
3534class Dot(Binary):
3535    @property
3536    def name(self) -> str:
3537        return self.expression.name
3538
3539    @property
3540    def output_name(self) -> str:
3541        return self.name
3542
3543    @classmethod
3544    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3545        """Build a Dot object with a sequence of expressions."""
3546        if len(expressions) < 2:
3547            raise ValueError(f"Dot requires >= 2 expressions.")
3548
3549        a, b, *expressions = expressions
3550        dot = Dot(this=a, expression=b)
3551
3552        for expression in expressions:
3553            dot = Dot(this=dot, expression=expression)
3554
3555        return dot
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3543    @classmethod
3544    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3545        """Build a Dot object with a sequence of expressions."""
3546        if len(expressions) < 2:
3547            raise ValueError(f"Dot requires >= 2 expressions.")
3548
3549        a, b, *expressions = expressions
3550        dot = Dot(this=a, expression=b)
3551
3552        for expression in expressions:
3553            dot = Dot(this=dot, expression=expression)
3554
3555        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3558class DPipe(Binary):
3559    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3562class SafeDPipe(DPipe):
3563    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3566class EQ(Binary, Predicate):
3567    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3570class NullSafeEQ(Binary, Predicate):
3571    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3574class NullSafeNEQ(Binary, Predicate):
3575    pass
key = 'nullsafeneq'
class Distance(Binary):
3578class Distance(Binary):
3579    pass
key = 'distance'
class Escape(Binary):
3582class Escape(Binary):
3583    pass
key = 'escape'
class Glob(Binary, Predicate):
3586class Glob(Binary, Predicate):
3587    pass
key = 'glob'
class GT(Binary, Predicate):
3590class GT(Binary, Predicate):
3591    pass
key = 'gt'
class GTE(Binary, Predicate):
3594class GTE(Binary, Predicate):
3595    pass
key = 'gte'
class ILike(Binary, Predicate):
3598class ILike(Binary, Predicate):
3599    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3602class ILikeAny(Binary, Predicate):
3603    pass
key = 'ilikeany'
class IntDiv(Binary):
3606class IntDiv(Binary):
3607    pass
key = 'intdiv'
class Is(Binary, Predicate):
3610class Is(Binary, Predicate):
3611    pass
key = 'is'
class Kwarg(Binary):
3614class Kwarg(Binary):
3615    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

key = 'kwarg'
class Like(Binary, Predicate):
3618class Like(Binary, Predicate):
3619    pass
key = 'like'
class LikeAny(Binary, Predicate):
3622class LikeAny(Binary, Predicate):
3623    pass
key = 'likeany'
class LT(Binary, Predicate):
3626class LT(Binary, Predicate):
3627    pass
key = 'lt'
class LTE(Binary, Predicate):
3630class LTE(Binary, Predicate):
3631    pass
key = 'lte'
class Mod(Binary):
3634class Mod(Binary):
3635    pass
key = 'mod'
class Mul(Binary):
3638class Mul(Binary):
3639    pass
key = 'mul'
class NEQ(Binary, Predicate):
3642class NEQ(Binary, Predicate):
3643    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3646class SimilarTo(Binary, Predicate):
3647    pass
key = 'similarto'
class Slice(Binary):
3650class Slice(Binary):
3651    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3654class Sub(Binary):
3655    pass
key = 'sub'
class ArrayOverlaps(Binary):
3658class ArrayOverlaps(Binary):
3659    pass
key = 'arrayoverlaps'
class Unary(Condition):
3664class Unary(Condition):
3665    pass
key = 'unary'
class BitwiseNot(Unary):
3668class BitwiseNot(Unary):
3669    pass
key = 'bitwisenot'
class Not(Unary):
3672class Not(Unary):
3673    pass
key = 'not'
class Paren(Unary):
3676class Paren(Unary):
3677    arg_types = {"this": True, "with": False}
3678
3679    @property
3680    def output_name(self) -> str:
3681        return self.this.name
arg_types = {'this': True, 'with': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'paren'
class Neg(Unary):
3684class Neg(Unary):
3685    pass
key = 'neg'
class Alias(Expression):
3688class Alias(Expression):
3689    arg_types = {"this": True, "alias": False}
3690
3691    @property
3692    def output_name(self) -> str:
3693        return self.alias
arg_types = {'this': True, 'alias': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'alias'
class Aliases(Expression):
3696class Aliases(Expression):
3697    arg_types = {"this": True, "expressions": True}
3698
3699    @property
3700    def aliases(self):
3701        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3704class AtTimeZone(Expression):
3705    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3708class Between(Predicate):
3709    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3712class Bracket(Condition):
3713    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3716class SafeBracket(Bracket):
3717    """Represents array lookup where OOB index yields NULL instead of causing a failure."""

Represents array lookup where OOB index yields NULL instead of causing a failure.

key = 'safebracket'
class Distinct(Expression):
3720class Distinct(Expression):
3721    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3724class In(Predicate):
3725    arg_types = {
3726        "this": True,
3727        "expressions": False,
3728        "query": False,
3729        "unnest": False,
3730        "field": False,
3731        "is_global": False,
3732    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3735class TimeUnit(Expression):
3736    """Automatically converts unit arg into a var."""
3737
3738    arg_types = {"unit": False}
3739
3740    def __init__(self, **args):
3741        unit = args.get("unit")
3742        if isinstance(unit, (Column, Literal)):
3743            args["unit"] = Var(this=unit.name)
3744        elif isinstance(unit, Week):
3745            unit.set("this", Var(this=unit.this.name))
3746
3747        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3740    def __init__(self, **args):
3741        unit = args.get("unit")
3742        if isinstance(unit, (Column, Literal)):
3743            args["unit"] = Var(this=unit.name)
3744        elif isinstance(unit, Week):
3745            unit.set("this", Var(this=unit.this.name))
3746
3747        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3750class Interval(TimeUnit):
3751    arg_types = {"this": False, "unit": False}
3752
3753    @property
3754    def unit(self) -> t.Optional[Var]:
3755        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3758class IgnoreNulls(Expression):
3759    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3762class RespectNulls(Expression):
3763    pass
key = 'respectnulls'
class Func(Condition):
3767class Func(Condition):
3768    """
3769    The base class for all function expressions.
3770
3771    Attributes:
3772        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3773            treated as a variable length argument and the argument's value will be stored as a list.
3774        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3775            for this function expression. These values are used to map this node to a name during parsing
3776            as well as to provide the function's name during SQL string generation. By default the SQL
3777            name is set to the expression's class name transformed to snake case.
3778    """
3779
3780    is_var_len_args = False
3781
3782    @classmethod
3783    def from_arg_list(cls, args):
3784        if cls.is_var_len_args:
3785            all_arg_keys = list(cls.arg_types)
3786            # If this function supports variable length argument treat the last argument as such.
3787            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3788            num_non_var = len(non_var_len_arg_keys)
3789
3790            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3791            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3792        else:
3793            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3794
3795        return cls(**args_dict)
3796
3797    @classmethod
3798    def sql_names(cls):
3799        if cls is Func:
3800            raise NotImplementedError(
3801                "SQL name is only supported by concrete function implementations"
3802            )
3803        if "_sql_names" not in cls.__dict__:
3804            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3805        return cls._sql_names
3806
3807    @classmethod
3808    def sql_name(cls):
3809        return cls.sql_names()[0]
3810
3811    @classmethod
3812    def default_parser_mappings(cls):
3813        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
is_var_len_args = False
@classmethod
def from_arg_list(cls, args):
3782    @classmethod
3783    def from_arg_list(cls, args):
3784        if cls.is_var_len_args:
3785            all_arg_keys = list(cls.arg_types)
3786            # If this function supports variable length argument treat the last argument as such.
3787            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3788            num_non_var = len(non_var_len_arg_keys)
3789
3790            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3791            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3792        else:
3793            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3794
3795        return cls(**args_dict)
@classmethod
def sql_names(cls):
3797    @classmethod
3798    def sql_names(cls):
3799        if cls is Func:
3800            raise NotImplementedError(
3801                "SQL name is only supported by concrete function implementations"
3802            )
3803        if "_sql_names" not in cls.__dict__:
3804            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3805        return cls._sql_names
@classmethod
def sql_name(cls):
3807    @classmethod
3808    def sql_name(cls):
3809        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3811    @classmethod
3812    def default_parser_mappings(cls):
3813        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3816class AggFunc(Func):
3817    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3820class ParameterizedAgg(AggFunc):
3821    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3824class Abs(Func):
3825    pass
key = 'abs'
class Anonymous(Func):
3828class Anonymous(Func):
3829    arg_types = {"this": True, "expressions": False}
3830    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3835class Hll(AggFunc):
3836    arg_types = {"this": True, "expressions": False}
3837    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3840class ApproxDistinct(AggFunc):
3841    arg_types = {"this": True, "accuracy": False}
3842    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3845class Array(Func):
3846    arg_types = {"expressions": False}
3847    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3851class ToChar(Func):
3852    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3855class GenerateSeries(Func):
3856    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3859class ArrayAgg(AggFunc):
3860    pass
key = 'arrayagg'
class ArrayAll(Func):
3863class ArrayAll(Func):
3864    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3867class ArrayAny(Func):
3868    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3871class ArrayConcat(Func):
3872    arg_types = {"this": True, "expressions": False}
3873    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3876class ArrayContains(Binary, Func):
3877    pass
key = 'arraycontains'
class ArrayContained(Binary):
3880class ArrayContained(Binary):
3881    pass
key = 'arraycontained'
class ArrayFilter(Func):
3884class ArrayFilter(Func):
3885    arg_types = {"this": True, "expression": True}
3886    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3889class ArrayJoin(Func):
3890    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3893class ArraySize(Func):
3894    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3897class ArraySort(Func):
3898    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3901class ArraySum(Func):
3902    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3905class ArrayUnionAgg(AggFunc):
3906    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3909class Avg(AggFunc):
3910    pass
key = 'avg'
class AnyValue(AggFunc):
3913class AnyValue(AggFunc):
3914    pass
key = 'anyvalue'
class Case(Func):
3917class Case(Func):
3918    arg_types = {"this": False, "ifs": True, "default": False}
3919
3920    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3921        instance = _maybe_copy(self, copy)
3922        instance.append(
3923            "ifs",
3924            If(
3925                this=maybe_parse(condition, copy=copy, **opts),
3926                true=maybe_parse(then, copy=copy, **opts),
3927            ),
3928        )
3929        return instance
3930
3931    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3932        instance = _maybe_copy(self, copy)
3933        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3934        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3920    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3921        instance = _maybe_copy(self, copy)
3922        instance.append(
3923            "ifs",
3924            If(
3925                this=maybe_parse(condition, copy=copy, **opts),
3926                true=maybe_parse(then, copy=copy, **opts),
3927            ),
3928        )
3929        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3931    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3932        instance = _maybe_copy(self, copy)
3933        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3934        return instance
key = 'case'
class Cast(Func):
3937class Cast(Func):
3938    arg_types = {"this": True, "to": True}
3939
3940    @property
3941    def name(self) -> str:
3942        return self.this.name
3943
3944    @property
3945    def to(self) -> DataType:
3946        return self.args["to"]
3947
3948    @property
3949    def output_name(self) -> str:
3950        return self.name
3951
3952    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3953        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True}
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3952    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3953        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3956class CastToStrType(Func):
3957    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3960class Collate(Binary):
3961    pass
key = 'collate'
class TryCast(Cast):
3964class TryCast(Cast):
3965    pass
key = 'trycast'
class Ceil(Func):
3968class Ceil(Func):
3969    arg_types = {"this": True, "decimals": False}
3970    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
3973class Coalesce(Func):
3974    arg_types = {"this": True, "expressions": False}
3975    is_var_len_args = True
3976    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
3979class Concat(Func):
3980    arg_types = {"expressions": True}
3981    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
3984class SafeConcat(Concat):
3985    pass
key = 'safeconcat'
class ConcatWs(Concat):
3988class ConcatWs(Concat):
3989    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
3992class Count(AggFunc):
3993    arg_types = {"this": False, "expressions": False}
3994    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
3997class CountIf(AggFunc):
3998    pass
key = 'countif'
class CurrentDate(Func):
4001class CurrentDate(Func):
4002    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4005class CurrentDatetime(Func):
4006    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4009class CurrentTime(Func):
4010    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4013class CurrentTimestamp(Func):
4014    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4017class CurrentUser(Func):
4018    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4021class DateAdd(Func, TimeUnit):
4022    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4025class DateSub(Func, TimeUnit):
4026    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4029class DateDiff(Func, TimeUnit):
4030    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4031    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4034class DateTrunc(Func):
4035    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4038class DatetimeAdd(Func, TimeUnit):
4039    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4042class DatetimeSub(Func, TimeUnit):
4043    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4046class DatetimeDiff(Func, TimeUnit):
4047    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4050class DatetimeTrunc(Func, TimeUnit):
4051    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4054class DayOfWeek(Func):
4055    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4058class DayOfMonth(Func):
4059    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4062class DayOfYear(Func):
4063    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4066class WeekOfYear(Func):
4067    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class LastDateOfMonth(Func):
4070class LastDateOfMonth(Func):
4071    pass
key = 'lastdateofmonth'
class Extract(Func):
4074class Extract(Func):
4075    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4078class TimestampAdd(Func, TimeUnit):
4079    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4082class TimestampSub(Func, TimeUnit):
4083    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4086class TimestampDiff(Func, TimeUnit):
4087    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4090class TimestampTrunc(Func, TimeUnit):
4091    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4094class TimeAdd(Func, TimeUnit):
4095    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4098class TimeSub(Func, TimeUnit):
4099    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4102class TimeDiff(Func, TimeUnit):
4103    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4106class TimeTrunc(Func, TimeUnit):
4107    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4110class DateFromParts(Func):
4111    _sql_names = ["DATEFROMPARTS"]
4112    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4115class DateStrToDate(Func):
4116    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4119class DateToDateStr(Func):
4120    pass
key = 'datetodatestr'
class DateToDi(Func):
4123class DateToDi(Func):
4124    pass
key = 'datetodi'
class Date(Func):
4127class Date(Func):
4128    arg_types = {"expressions": True}
4129    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'date'
class Day(Func):
4132class Day(Func):
4133    pass
key = 'day'
class Decode(Func):
4136class Decode(Func):
4137    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4140class DiToDate(Func):
4141    pass
key = 'ditodate'
class Encode(Func):
4144class Encode(Func):
4145    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4148class Exp(Func):
4149    pass
key = 'exp'
class Explode(Func):
4152class Explode(Func):
4153    pass
key = 'explode'
class Floor(Func):
4156class Floor(Func):
4157    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4160class FromBase64(Func):
4161    pass
key = 'frombase64'
class ToBase64(Func):
4164class ToBase64(Func):
4165    pass
key = 'tobase64'
class Greatest(Func):
4168class Greatest(Func):
4169    arg_types = {"this": True, "expressions": False}
4170    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4173class GroupConcat(Func):
4174    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4177class Hex(Func):
4178    pass
key = 'hex'
class If(Func):
4181class If(Func):
4182    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4185class Initcap(Func):
4186    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4189class JSONKeyValue(Expression):
4190    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4193class JSONObject(Func):
4194    arg_types = {
4195        "expressions": False,
4196        "null_handling": False,
4197        "unique_keys": False,
4198        "return_type": False,
4199        "format_json": False,
4200        "encoding": False,
4201    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4204class OpenJSONColumnDef(Expression):
4205    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
arg_types = {'this': True, 'kind': True, 'path': False, 'as_json': False}
key = 'openjsoncolumndef'
class OpenJSON(Func):
4208class OpenJSON(Func):
4209    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4212class JSONBContains(Binary):
4213    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4216class JSONExtract(Binary, Func):
4217    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4220class JSONExtractScalar(JSONExtract):
4221    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4224class JSONBExtract(JSONExtract):
4225    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4228class JSONBExtractScalar(JSONExtract):
4229    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4232class JSONFormat(Func):
4233    arg_types = {"this": False, "options": False}
4234    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class Least(Func):
4237class Least(Func):
4238    arg_types = {"expressions": False}
4239    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4242class Left(Func):
4243    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4250class Length(Func):
4251    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4254class Levenshtein(Func):
4255    arg_types = {
4256        "this": True,
4257        "expression": False,
4258        "ins_cost": False,
4259        "del_cost": False,
4260        "sub_cost": False,
4261    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4264class Ln(Func):
4265    pass
key = 'ln'
class Log(Func):
4268class Log(Func):
4269    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4272class Log2(Func):
4273    pass
key = 'log2'
class Log10(Func):
4276class Log10(Func):
4277    pass
key = 'log10'
class LogicalOr(AggFunc):
4280class LogicalOr(AggFunc):
4281    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4284class LogicalAnd(AggFunc):
4285    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4288class Lower(Func):
4289    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4292class Map(Func):
4293    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4296class MapFromEntries(Func):
4297    pass
key = 'mapfromentries'
class StarMap(Func):
4300class StarMap(Func):
4301    pass
key = 'starmap'
class VarMap(Func):
4304class VarMap(Func):
4305    arg_types = {"keys": True, "values": True}
4306    is_var_len_args = True
4307
4308    @property
4309    def keys(self) -> t.List[Expression]:
4310        return self.args["keys"].expressions
4311
4312    @property
4313    def values(self) -> t.List[Expression]:
4314        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4318class MatchAgainst(Func):
4319    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4322class Max(AggFunc):
4323    arg_types = {"this": True, "expressions": False}
4324    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4327class MD5(Func):
4328    _sql_names = ["MD5"]
key = 'md5'
class Min(AggFunc):
4331class Min(AggFunc):
4332    arg_types = {"this": True, "expressions": False}
4333    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4336class Month(Func):
4337    pass
key = 'month'
class Nvl2(Func):
4340class Nvl2(Func):
4341    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4344class Posexplode(Func):
4345    pass
key = 'posexplode'
class Pow(Binary, Func):
4348class Pow(Binary, Func):
4349    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4352class PercentileCont(AggFunc):
4353    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4356class PercentileDisc(AggFunc):
4357    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4360class Quantile(AggFunc):
4361    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4364class ApproxQuantile(Quantile):
4365    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
arg_types = {'this': True, 'quantile': True, 'accuracy': False, 'weight': False}
key = 'approxquantile'
class RangeN(Func):
4368class RangeN(Func):
4369    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4372class ReadCSV(Func):
4373    _sql_names = ["READ_CSV"]
4374    is_var_len_args = True
4375    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4378class Reduce(Func):
4379    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
arg_types = {'this': True, 'initial': True, 'merge': True, 'finish': False}
key = 'reduce'
class RegexpExtract(Func):
4382class RegexpExtract(Func):
4383    arg_types = {
4384        "this": True,
4385        "expression": True,
4386        "position": False,
4387        "occurrence": False,
4388        "group": False,
4389    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4392class RegexpLike(Func):
4393    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4396class RegexpILike(Func):
4397    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4402class RegexpSplit(Func):
4403    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4406class Repeat(Func):
4407    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4410class Round(Func):
4411    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4414class RowNumber(Func):
4415    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4418class SafeDivide(Func):
4419    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4422class SetAgg(AggFunc):
4423    pass
key = 'setagg'
class SHA(Func):
4426class SHA(Func):
4427    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4430class SHA2(Func):
4431    _sql_names = ["SHA2"]
4432    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4435class SortArray(Func):
4436    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4439class Split(Func):
4440    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4445class Substring(Func):
4446    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4449class StandardHash(Func):
4450    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4453class StrPosition(Func):
4454    arg_types = {
4455        "this": True,
4456        "substr": True,
4457        "position": False,
4458        "instance": False,
4459    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4462class StrToDate(Func):
4463    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4466class StrToTime(Func):
4467    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtotime'
class StrToUnix(Func):
4472class StrToUnix(Func):
4473    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4476class NumberToStr(Func):
4477    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4480class FromBase(Func):
4481    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4484class Struct(Func):
4485    arg_types = {"expressions": True}
4486    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4489class StructExtract(Func):
4490    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4493class Sum(AggFunc):
4494    pass
key = 'sum'
class Sqrt(Func):
4497class Sqrt(Func):
4498    pass
key = 'sqrt'
class Stddev(AggFunc):
4501class Stddev(AggFunc):
4502    pass
key = 'stddev'
class StddevPop(AggFunc):
4505class StddevPop(AggFunc):
4506    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4509class StddevSamp(AggFunc):
4510    pass
key = 'stddevsamp'
class TimeToStr(Func):
4513class TimeToStr(Func):
4514    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4517class TimeToTimeStr(Func):
4518    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4521class TimeToUnix(Func):
4522    pass
key = 'timetounix'
class TimeStrToDate(Func):
4525class TimeStrToDate(Func):
4526    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4529class TimeStrToTime(Func):
4530    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4533class TimeStrToUnix(Func):
4534    pass
key = 'timestrtounix'
class Trim(Func):
4537class Trim(Func):
4538    arg_types = {
4539        "this": True,
4540        "expression": False,
4541        "position": False,
4542        "collation": False,
4543    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4546class TsOrDsAdd(Func, TimeUnit):
4547    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4550class TsOrDsToDateStr(Func):
4551    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4554class TsOrDsToDate(Func):
4555    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4558class TsOrDiToDi(Func):
4559    pass
key = 'tsorditodi'
class Unhex(Func):
4562class Unhex(Func):
4563    pass
key = 'unhex'
class UnixToStr(Func):
4566class UnixToStr(Func):
4567    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4572class UnixToTime(Func):
4573    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4574
4575    SECONDS = Literal.string("seconds")
4576    MILLIS = Literal.string("millis")
4577    MICROS = Literal.string("micros")
arg_types = {'this': True, 'scale': False, 'zone': False, 'hours': False, 'minutes': False}
SECONDS = (LITERAL this: seconds, is_string: True)
MILLIS = (LITERAL this: millis, is_string: True)
MICROS = (LITERAL this: micros, is_string: True)
key = 'unixtotime'
class UnixToTimeStr(Func):
4580class UnixToTimeStr(Func):
4581    pass
key = 'unixtotimestr'
class Upper(Func):
4584class Upper(Func):
4585    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4588class Variance(AggFunc):
4589    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4592class VariancePop(AggFunc):
4593    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4596class Week(Func):
4597    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4600class XMLTable(Func):
4601    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
arg_types = {'this': True, 'passing': False, 'columns': False, 'by_ref': False}
key = 'xmltable'
class Year(Func):
4604class Year(Func):
4605    pass
key = 'year'
class Use(Expression):
4608class Use(Expression):
4609    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4612class Merge(Expression):
4613    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
arg_types = {'this': True, 'using': True, 'on': True, 'expressions': True}
key = 'merge'
class When(Func):
4616class When(Func):
4617    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
arg_types = {'matched': True, 'source': False, 'condition': False, 'then': True}
key = 'when'
class NextValueFor(Func):
4622class NextValueFor(Func):
4623    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4660def maybe_parse(
4661    sql_or_expression: ExpOrStr,
4662    *,
4663    into: t.Optional[IntoType] = None,
4664    dialect: DialectType = None,
4665    prefix: t.Optional[str] = None,
4666    copy: bool = False,
4667    **opts,
4668) -> Expression:
4669    """Gracefully handle a possible string or expression.
4670
4671    Example:
4672        >>> maybe_parse("1")
4673        (LITERAL this: 1, is_string: False)
4674        >>> maybe_parse(to_identifier("x"))
4675        (IDENTIFIER this: x, quoted: False)
4676
4677    Args:
4678        sql_or_expression: the SQL code string or an expression
4679        into: the SQLGlot Expression to parse into
4680        dialect: the dialect used to parse the input expressions (in the case that an
4681            input expression is a SQL string).
4682        prefix: a string to prefix the sql with before it gets parsed
4683            (automatically includes a space)
4684        copy: whether or not to copy the expression.
4685        **opts: other options to use to parse the input expressions (again, in the case
4686            that an input expression is a SQL string).
4687
4688    Returns:
4689        Expression: the parsed or given expression.
4690    """
4691    if isinstance(sql_or_expression, Expression):
4692        if copy:
4693            return sql_or_expression.copy()
4694        return sql_or_expression
4695
4696    if sql_or_expression is None:
4697        raise ParseError(f"SQL cannot be None")
4698
4699    import sqlglot
4700
4701    sql = str(sql_or_expression)
4702    if prefix:
4703        sql = f"{prefix} {sql}"
4704
4705    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
4889def union(
4890    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4891) -> Union:
4892    """
4893    Initializes a syntax tree from one UNION expression.
4894
4895    Example:
4896        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4897        'SELECT * FROM foo UNION SELECT * FROM bla'
4898
4899    Args:
4900        left: the SQL code string corresponding to the left-hand side.
4901            If an `Expression` instance is passed, it will be used as-is.
4902        right: the SQL code string corresponding to the right-hand side.
4903            If an `Expression` instance is passed, it will be used as-is.
4904        distinct: set the DISTINCT flag if and only if this is true.
4905        dialect: the dialect used to parse the input expression.
4906        opts: other options to use to parse the input expressions.
4907
4908    Returns:
4909        The new Union instance.
4910    """
4911    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4912    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4913
4914    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union instance.

def intersect( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Intersect:
4917def intersect(
4918    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4919) -> Intersect:
4920    """
4921    Initializes a syntax tree from one INTERSECT expression.
4922
4923    Example:
4924        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4925        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4926
4927    Args:
4928        left: the SQL code string corresponding to the left-hand side.
4929            If an `Expression` instance is passed, it will be used as-is.
4930        right: the SQL code string corresponding to the right-hand side.
4931            If an `Expression` instance is passed, it will be used as-is.
4932        distinct: set the DISTINCT flag if and only if this is true.
4933        dialect: the dialect used to parse the input expression.
4934        opts: other options to use to parse the input expressions.
4935
4936    Returns:
4937        The new Intersect instance.
4938    """
4939    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4940    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4941
4942    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect instance.

def except_( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Except:
4945def except_(
4946    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4947) -> Except:
4948    """
4949    Initializes a syntax tree from one EXCEPT expression.
4950
4951    Example:
4952        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4953        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4954
4955    Args:
4956        left: the SQL code string corresponding to the left-hand side.
4957            If an `Expression` instance is passed, it will be used as-is.
4958        right: the SQL code string corresponding to the right-hand side.
4959            If an `Expression` instance is passed, it will be used as-is.
4960        distinct: set the DISTINCT flag if and only if this is true.
4961        dialect: the dialect used to parse the input expression.
4962        opts: other options to use to parse the input expressions.
4963
4964    Returns:
4965        The new Except instance.
4966    """
4967    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4968    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4969
4970    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except instance.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4973def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4974    """
4975    Initializes a syntax tree from one or multiple SELECT expressions.
4976
4977    Example:
4978        >>> select("col1", "col2").from_("tbl").sql()
4979        'SELECT col1, col2 FROM tbl'
4980
4981    Args:
4982        *expressions: the SQL code string to parse as the expressions of a
4983            SELECT statement. If an Expression instance is passed, this is used as-is.
4984        dialect: the dialect used to parse the input expressions (in the case that an
4985            input expression is a SQL string).
4986        **opts: other options to use to parse the input expressions (again, in the case
4987            that an input expression is a SQL string).
4988
4989    Returns:
4990        Select: the syntax tree for the SELECT statement.
4991    """
4992    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4995def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4996    """
4997    Initializes a syntax tree from a FROM expression.
4998
4999    Example:
5000        >>> from_("tbl").select("col1", "col2").sql()
5001        'SELECT col1, col2 FROM tbl'
5002
5003    Args:
5004        *expression: the SQL code string to parse as the FROM expressions of a
5005            SELECT statement. If an Expression instance is passed, this is used as-is.
5006        dialect: the dialect used to parse the input expression (in the case that the
5007            input expression is a SQL string).
5008        **opts: other options to use to parse the input expressions (again, in the case
5009            that the input expression is a SQL string).
5010
5011    Returns:
5012        Select: the syntax tree for the SELECT statement.
5013    """
5014    return Select().from_(expression, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
5017def update(
5018    table: str | Table,
5019    properties: dict,
5020    where: t.Optional[ExpOrStr] = None,
5021    from_: t.Optional[ExpOrStr] = None,
5022    dialect: DialectType = None,
5023    **opts,
5024) -> Update:
5025    """
5026    Creates an update statement.
5027
5028    Example:
5029        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5030        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5031
5032    Args:
5033        *properties: dictionary of properties to set which are
5034            auto converted to sql objects eg None -> NULL
5035        where: sql conditional parsed into a WHERE statement
5036        from_: sql statement parsed into a FROM statement
5037        dialect: the dialect used to parse the input expressions.
5038        **opts: other options to use to parse the input expressions.
5039
5040    Returns:
5041        Update: the syntax tree for the UPDATE statement.
5042    """
5043    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5044    update_expr.set(
5045        "expressions",
5046        [
5047            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5048            for k, v in properties.items()
5049        ],
5050    )
5051    if from_:
5052        update_expr.set(
5053            "from",
5054            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5055        )
5056    if isinstance(where, Condition):
5057        where = Where(this=where)
5058    if where:
5059        update_expr.set(
5060            "where",
5061            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5062        )
5063    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
5066def delete(
5067    table: ExpOrStr,
5068    where: t.Optional[ExpOrStr] = None,
5069    returning: t.Optional[ExpOrStr] = None,
5070    dialect: DialectType = None,
5071    **opts,
5072) -> Delete:
5073    """
5074    Builds a delete statement.
5075
5076    Example:
5077        >>> delete("my_table", where="id > 1").sql()
5078        'DELETE FROM my_table WHERE id > 1'
5079
5080    Args:
5081        where: sql conditional parsed into a WHERE statement
5082        returning: sql conditional parsed into a RETURNING statement
5083        dialect: the dialect used to parse the input expressions.
5084        **opts: other options to use to parse the input expressions.
5085
5086    Returns:
5087        Delete: the syntax tree for the DELETE statement.
5088    """
5089    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5090    if where:
5091        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5092    if returning:
5093        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5094    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def insert( expression: Union[str, sqlglot.expressions.Expression], into: Union[str, sqlglot.expressions.Expression], columns: Optional[Sequence[Union[str, sqlglot.expressions.Expression]]] = None, overwrite: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
5097def insert(
5098    expression: ExpOrStr,
5099    into: ExpOrStr,
5100    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5101    overwrite: t.Optional[bool] = None,
5102    dialect: DialectType = None,
5103    copy: bool = True,
5104    **opts,
5105) -> Insert:
5106    """
5107    Builds an INSERT statement.
5108
5109    Example:
5110        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5111        'INSERT INTO tbl VALUES (1, 2, 3)'
5112
5113    Args:
5114        expression: the sql string or expression of the INSERT statement
5115        into: the tbl to insert data to.
5116        columns: optionally the table's column names.
5117        overwrite: whether to INSERT OVERWRITE or not.
5118        dialect: the dialect used to parse the input expressions.
5119        copy: whether or not to copy the expression.
5120        **opts: other options to use to parse the input expressions.
5121
5122    Returns:
5123        Insert: the syntax tree for the INSERT statement.
5124    """
5125    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5126    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5127
5128    if columns:
5129        this = _apply_list_builder(
5130            *columns,
5131            instance=Schema(this=this),
5132            arg="expressions",
5133            into=Identifier,
5134            copy=False,
5135            dialect=dialect,
5136            **opts,
5137        )
5138
5139    return Insert(this=this, expression=expr, overwrite=overwrite)

Builds an INSERT statement.

Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql()
'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
  • expression: the sql string or expression of the INSERT statement
  • into: the tbl to insert data to.
  • columns: optionally the table's column names.
  • overwrite: whether to INSERT OVERWRITE or not.
  • dialect: the dialect used to parse the input expressions.
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Insert: the syntax tree for the INSERT statement.

def condition( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5142def condition(
5143    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5144) -> Condition:
5145    """
5146    Initialize a logical condition expression.
5147
5148    Example:
5149        >>> condition("x=1").sql()
5150        'x = 1'
5151
5152        This is helpful for composing larger logical syntax trees:
5153        >>> where = condition("x=1")
5154        >>> where = where.and_("y=1")
5155        >>> Select().from_("tbl").select("*").where(where).sql()
5156        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5157
5158    Args:
5159        *expression: the SQL code string to parse.
5160            If an Expression instance is passed, this is used as-is.
5161        dialect: the dialect used to parse the input expression (in the case that the
5162            input expression is a SQL string).
5163        copy: Whether or not to copy `expression` (only applies to expressions).
5164        **opts: other options to use to parse the input expressions (again, in the case
5165            that the input expression is a SQL string).
5166
5167    Returns:
5168        The new Condition instance
5169    """
5170    return maybe_parse(
5171        expression,
5172        into=Condition,
5173        dialect=dialect,
5174        copy=copy,
5175        **opts,
5176    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy: Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

The new Condition instance

def and_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5179def and_(
5180    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5181) -> Condition:
5182    """
5183    Combine multiple conditions with an AND logical operator.
5184
5185    Example:
5186        >>> and_("x=1", and_("y=1", "z=1")).sql()
5187        'x = 1 AND (y = 1 AND z = 1)'
5188
5189    Args:
5190        *expressions: the SQL code strings to parse.
5191            If an Expression instance is passed, this is used as-is.
5192        dialect: the dialect used to parse the input expression.
5193        copy: whether or not to copy `expressions` (only applies to Expressions).
5194        **opts: other options to use to parse the input expressions.
5195
5196    Returns:
5197        And: the new condition
5198    """
5199    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5202def or_(
5203    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5204) -> Condition:
5205    """
5206    Combine multiple conditions with an OR logical operator.
5207
5208    Example:
5209        >>> or_("x=1", or_("y=1", "z=1")).sql()
5210        'x = 1 OR (y = 1 OR z = 1)'
5211
5212    Args:
5213        *expressions: the SQL code strings to parse.
5214            If an Expression instance is passed, this is used as-is.
5215        dialect: the dialect used to parse the input expression.
5216        copy: whether or not to copy `expressions` (only applies to Expressions).
5217        **opts: other options to use to parse the input expressions.
5218
5219    Returns:
5220        Or: the new condition
5221    """
5222    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Not:
5225def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5226    """
5227    Wrap a condition with a NOT operator.
5228
5229    Example:
5230        >>> not_("this_suit='black'").sql()
5231        "NOT this_suit = 'black'"
5232
5233    Args:
5234        expression: the SQL code string to parse.
5235            If an Expression instance is passed, this is used as-is.
5236        dialect: the dialect used to parse the input expression.
5237        copy: whether to copy the expression or not.
5238        **opts: other options to use to parse the input expressions.
5239
5240    Returns:
5241        The new condition.
5242    """
5243    this = condition(
5244        expression,
5245        dialect=dialect,
5246        copy=copy,
5247        **opts,
5248    )
5249    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression or not.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition.

def paren( expression: Union[str, sqlglot.expressions.Expression], copy: bool = True) -> sqlglot.expressions.Paren:
5252def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5253    """
5254    Wrap an expression in parentheses.
5255
5256    Example:
5257        >>> paren("5 + 3").sql()
5258        '(5 + 3)'
5259
5260    Args:
5261        expression: the SQL code string to parse.
5262            If an Expression instance is passed, this is used as-is.
5263        copy: whether to copy the expression or not.
5264
5265    Returns:
5266        The wrapped expression.
5267    """
5268    return Paren(this=maybe_parse(expression, copy=copy))

Wrap an expression in parentheses.

Example:
>>> paren("5 + 3").sql()
'(5 + 3)'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • copy: whether to copy the expression or not.
Returns:

The wrapped expression.

SAFE_IDENTIFIER_RE = re.compile('^[_a-zA-Z][\\w]*$')
def to_identifier(name, quoted=None, copy=True):
5286def to_identifier(name, quoted=None, copy=True):
5287    """Builds an identifier.
5288
5289    Args:
5290        name: The name to turn into an identifier.
5291        quoted: Whether or not force quote the identifier.
5292        copy: Whether or not to copy a passed in Identefier node.
5293
5294    Returns:
5295        The identifier ast node.
5296    """
5297
5298    if name is None:
5299        return None
5300
5301    if isinstance(name, Identifier):
5302        identifier = _maybe_copy(name, copy)
5303    elif isinstance(name, str):
5304        identifier = Identifier(
5305            this=name,
5306            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5307        )
5308    else:
5309        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5310    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
  • copy: Whether or not to copy a passed in Identefier node.
Returns:

The identifier ast node.

INTERVAL_STRING_RE = re.compile('\\s*([0-9]+)\\s*([a-zA-Z]+)\\s*')
def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
5316def to_interval(interval: str | Literal) -> Interval:
5317    """Builds an interval expression from a string like '1 day' or '5 months'."""
5318    if isinstance(interval, Literal):
5319        if not interval.is_string:
5320            raise ValueError("Invalid interval string.")
5321
5322        interval = interval.this
5323
5324    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5325
5326    if not interval_parts:
5327        raise ValueError("Invalid interval string.")
5328
5329    return Interval(
5330        this=Literal.string(interval_parts.group(1)),
5331        unit=Var(this=interval_parts.group(2)),
5332    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[sqlglot.expressions.Table]:
5345def to_table(
5346    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5347) -> t.Optional[Table]:
5348    """
5349    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5350    If a table is passed in then that table is returned.
5351
5352    Args:
5353        sql_path: a `[catalog].[schema].[table]` string.
5354        dialect: the source dialect according to which the table name will be parsed.
5355        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5356
5357    Returns:
5358        A table expression.
5359    """
5360    if sql_path is None or isinstance(sql_path, Table):
5361        return sql_path
5362    if not isinstance(sql_path, str):
5363        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5364
5365    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5366    if table:
5367        for k, v in kwargs.items():
5368            table.set(k, v)
5369
5370    return table

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
  • dialect: the source dialect according to which the table name will be parsed.
  • kwargs: the kwargs to instantiate the resulting Table expression with.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
5373def to_column(sql_path: str | Column, **kwargs) -> Column:
5374    """
5375    Create a column from a `[table].[column]` sql path. Schema is optional.
5376
5377    If a column is passed in then that column is returned.
5378
5379    Args:
5380        sql_path: `[table].[column]` string
5381    Returns:
5382        Table: A column expression
5383    """
5384    if sql_path is None or isinstance(sql_path, Column):
5385        return sql_path
5386    if not isinstance(sql_path, str):
5387        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5388    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
5391def alias_(
5392    expression: ExpOrStr,
5393    alias: str | Identifier,
5394    table: bool | t.Sequence[str | Identifier] = False,
5395    quoted: t.Optional[bool] = None,
5396    dialect: DialectType = None,
5397    copy: bool = True,
5398    **opts,
5399):
5400    """Create an Alias expression.
5401
5402    Example:
5403        >>> alias_('foo', 'bar').sql()
5404        'foo AS bar'
5405
5406        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5407        '(SELECT 1, 2) AS bar(a, b)'
5408
5409    Args:
5410        expression: the SQL code strings to parse.
5411            If an Expression instance is passed, this is used as-is.
5412        alias: the alias name to use. If the name has
5413            special characters it is quoted.
5414        table: Whether or not to create a table alias, can also be a list of columns.
5415        quoted: whether or not to quote the alias
5416        dialect: the dialect used to parse the input expression.
5417        copy: Whether or not to copy the expression.
5418        **opts: other options to use to parse the input expressions.
5419
5420    Returns:
5421        Alias: the aliased expression
5422    """
5423    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5424    alias = to_identifier(alias, quoted=quoted)
5425
5426    if table:
5427        table_alias = TableAlias(this=alias)
5428        exp.set("alias", table_alias)
5429
5430        if not isinstance(table, bool):
5431            for column in table:
5432                table_alias.append("columns", to_identifier(column, quoted=quoted))
5433
5434        return exp
5435
5436    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5437    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5438    # for the complete Window expression.
5439    #
5440    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5441
5442    if "alias" in exp.arg_types and not isinstance(exp, Window):
5443        exp.set("alias", alias)
5444        return exp
5445    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery( expression: Union[str, sqlglot.expressions.Expression], alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5448def subquery(
5449    expression: ExpOrStr,
5450    alias: t.Optional[Identifier | str] = None,
5451    dialect: DialectType = None,
5452    **opts,
5453) -> Select:
5454    """
5455    Build a subquery expression.
5456
5457    Example:
5458        >>> subquery('select x from tbl', 'bar').select('x').sql()
5459        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5460
5461    Args:
5462        expression: the SQL code strings to parse.
5463            If an Expression instance is passed, this is used as-is.
5464        alias: the alias name to use.
5465        dialect: the dialect used to parse the input expression.
5466        **opts: other options to use to parse the input expressions.
5467
5468    Returns:
5469        A new Select instance with the subquery expression included.
5470    """
5471
5472    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5473    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use.
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

A new Select instance with the subquery expression included.

def column( col: str | sqlglot.expressions.Identifier, table: Union[sqlglot.expressions.Identifier, str, NoneType] = None, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5476def column(
5477    col: str | Identifier,
5478    table: t.Optional[str | Identifier] = None,
5479    db: t.Optional[str | Identifier] = None,
5480    catalog: t.Optional[str | Identifier] = None,
5481    quoted: t.Optional[bool] = None,
5482) -> Column:
5483    """
5484    Build a Column.
5485
5486    Args:
5487        col: Column name.
5488        table: Table name.
5489        db: Database name.
5490        catalog: Catalog name.
5491        quoted: Whether to force quotes on the column's identifiers.
5492
5493    Returns:
5494        The new Column instance.
5495    """
5496    return Column(
5497        this=to_identifier(col, quoted=quoted),
5498        table=to_identifier(table, quoted=quoted),
5499        db=to_identifier(db, quoted=quoted),
5500        catalog=to_identifier(catalog, quoted=quoted),
5501    )

Build a Column.

Arguments:
  • col: Column name.
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quoted: Whether to force quotes on the column's identifiers.
Returns:

The new Column instance.

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5504def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5505    """Cast an expression to a data type.
5506
5507    Example:
5508        >>> cast('x + 1', 'int').sql()
5509        'CAST(x + 1 AS INT)'
5510
5511    Args:
5512        expression: The expression to cast.
5513        to: The datatype to cast to.
5514
5515    Returns:
5516        The new Cast instance.
5517    """
5518    expression = maybe_parse(expression, **opts)
5519    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

The new Cast instance.

def table_( table: sqlglot.expressions.Identifier | str, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None) -> sqlglot.expressions.Table:
5522def table_(
5523    table: Identifier | str,
5524    db: t.Optional[Identifier | str] = None,
5525    catalog: t.Optional[Identifier | str] = None,
5526    quoted: t.Optional[bool] = None,
5527    alias: t.Optional[Identifier | str] = None,
5528) -> Table:
5529    """Build a Table.
5530
5531    Args:
5532        table: Table name.
5533        db: Database name.
5534        catalog: Catalog name.
5535        quote: Whether to force quotes on the table's identifiers.
5536        alias: Table's alias.
5537
5538    Returns:
5539        The new Table instance.
5540    """
5541    return Table(
5542        this=to_identifier(table, quoted=quoted),
5543        db=to_identifier(db, quoted=quoted),
5544        catalog=to_identifier(catalog, quoted=quoted),
5545        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5546    )

Build a Table.

Arguments:
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quote: Whether to force quotes on the table's identifiers.
  • alias: Table's alias.
Returns:

The new Table instance.

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5549def values(
5550    values: t.Iterable[t.Tuple[t.Any, ...]],
5551    alias: t.Optional[str] = None,
5552    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5553) -> Values:
5554    """Build VALUES statement.
5555
5556    Example:
5557        >>> values([(1, '2')]).sql()
5558        "VALUES (1, '2')"
5559
5560    Args:
5561        values: values statements that will be converted to SQL
5562        alias: optional alias
5563        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5564         If either are provided then an alias is also required.
5565
5566    Returns:
5567        Values: the Values expression object
5568    """
5569    if columns and not alias:
5570        raise ValueError("Alias is required when providing columns")
5571
5572    return Values(
5573        expressions=[convert(tup) for tup in values],
5574        alias=(
5575            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5576            if columns
5577            else (TableAlias(this=to_identifier(alias)) if alias else None)
5578        ),
5579    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
5582def var(name: t.Optional[ExpOrStr]) -> Var:
5583    """Build a SQL variable.
5584
5585    Example:
5586        >>> repr(var('x'))
5587        '(VAR this: x)'
5588
5589        >>> repr(var(column('x', table='y')))
5590        '(VAR this: x)'
5591
5592    Args:
5593        name: The name of the var or an expression who's name will become the var.
5594
5595    Returns:
5596        The new variable node.
5597    """
5598    if not name:
5599        raise ValueError("Cannot convert empty name into var.")
5600
5601    if isinstance(name, Expression):
5602        name = name.name
5603    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
5606def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5607    """Build ALTER TABLE... RENAME... expression
5608
5609    Args:
5610        old_name: The old name of the table
5611        new_name: The new name of the table
5612
5613    Returns:
5614        Alter table expression
5615    """
5616    old_table = to_table(old_name)
5617    new_table = to_table(new_name)
5618    return AlterTable(
5619        this=old_table,
5620        actions=[
5621            RenameTable(this=new_table),
5622        ],
5623    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> sqlglot.expressions.Expression:
5626def convert(value: t.Any, copy: bool = False) -> Expression:
5627    """Convert a python value into an expression object.
5628
5629    Raises an error if a conversion is not possible.
5630
5631    Args:
5632        value: A python object.
5633        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5634
5635    Returns:
5636        Expression: the equivalent expression object.
5637    """
5638    if isinstance(value, Expression):
5639        return _maybe_copy(value, copy)
5640    if isinstance(value, str):
5641        return Literal.string(value)
5642    if isinstance(value, bool):
5643        return Boolean(this=value)
5644    if value is None or (isinstance(value, float) and math.isnan(value)):
5645        return NULL
5646    if isinstance(value, numbers.Number):
5647        return Literal.number(value)
5648    if isinstance(value, datetime.datetime):
5649        datetime_literal = Literal.string(
5650            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5651        )
5652        return TimeStrToTime(this=datetime_literal)
5653    if isinstance(value, datetime.date):
5654        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5655        return DateStrToDate(this=date_literal)
5656    if isinstance(value, tuple):
5657        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5658    if isinstance(value, list):
5659        return Array(expressions=[convert(v, copy=copy) for v in value])
5660    if isinstance(value, dict):
5661        return Map(
5662            keys=[convert(k, copy=copy) for k in value],
5663            values=[convert(v, copy=copy) for v in value.values()],
5664        )
5665    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children( expression: sqlglot.expressions.Expression, fun: Callable, *args, **kwargs) -> None:
5668def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5669    """
5670    Replace children of an expression with the result of a lambda fun(child) -> exp.
5671    """
5672    for k, v in expression.args.items():
5673        is_list_arg = type(v) is list
5674
5675        child_nodes = v if is_list_arg else [v]
5676        new_child_nodes = []
5677
5678        for cn in child_nodes:
5679            if isinstance(cn, Expression):
5680                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5681                    new_child_nodes.append(child_node)
5682                    child_node.parent = expression
5683                    child_node.arg_key = k
5684            else:
5685                new_child_nodes.append(cn)
5686
5687        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names( expression: sqlglot.expressions.Expression, exclude: str = '') -> Set[str]:
5690def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5691    """
5692    Return all table names referenced through columns in an expression.
5693
5694    Example:
5695        >>> import sqlglot
5696        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5697        ['a', 'c']
5698
5699    Args:
5700        expression: expression to find table names.
5701        exclude: a table name to exclude
5702
5703    Returns:
5704        A list of unique names.
5705    """
5706    return {
5707        table
5708        for table in (column.table for column in expression.find_all(Column))
5709        if table and table != exclude
5710    }

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
['a', 'c']
Arguments:
  • expression: expression to find table names.
  • exclude: a table name to exclude
Returns:

A list of unique names.

def table_name( table: sqlglot.expressions.Table | str, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) -> str:
5713def table_name(table: Table | str, dialect: DialectType = None) -> str:
5714    """Get the full name of a table as a string.
5715
5716    Args:
5717        table: Table expression node or string.
5718        dialect: The dialect to generate the table name for.
5719
5720    Examples:
5721        >>> from sqlglot import exp, parse_one
5722        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5723        'a.b.c'
5724
5725    Returns:
5726        The table name.
5727    """
5728
5729    table = maybe_parse(table, into=Table)
5730
5731    if not table:
5732        raise ValueError(f"Cannot parse {table}")
5733
5734    return ".".join(
5735        part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
5736        for part in table.parts
5737    )

Get the full name of a table as a string.

Arguments:
  • table: Table expression node or string.
  • dialect: The dialect to generate the table name for.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression: ~E, mapping: Dict[str, str], copy: bool = True) -> ~E:
5740def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5741    """Replace all tables in expression according to the mapping.
5742
5743    Args:
5744        expression: expression node to be transformed and replaced.
5745        mapping: mapping of table names.
5746        copy: whether or not to copy the expression.
5747
5748    Examples:
5749        >>> from sqlglot import exp, parse_one
5750        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5751        'SELECT * FROM c'
5752
5753    Returns:
5754        The mapped expression.
5755    """
5756
5757    def _replace_tables(node: Expression) -> Expression:
5758        if isinstance(node, Table):
5759            new_name = mapping.get(table_name(node))
5760            if new_name:
5761                return to_table(
5762                    new_name,
5763                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5764                )
5765        return node
5766
5767    return expression.transform(_replace_tables, copy=copy)

Replace all tables in expression according to the mapping.

Arguments:
  • expression: expression node to be transformed and replaced.
  • mapping: mapping of table names.
  • copy: whether or not to copy the expression.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders( expression: sqlglot.expressions.Expression, *args, **kwargs) -> sqlglot.expressions.Expression:
5770def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5771    """Replace placeholders in an expression.
5772
5773    Args:
5774        expression: expression node to be transformed and replaced.
5775        args: positional names that will substitute unnamed placeholders in the given order.
5776        kwargs: keyword arguments that will substitute named placeholders.
5777
5778    Examples:
5779        >>> from sqlglot import exp, parse_one
5780        >>> replace_placeholders(
5781        ...     parse_one("select * from :tbl where ? = ?"),
5782        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5783        ... ).sql()
5784        "SELECT * FROM foo WHERE str_col = 'b'"
5785
5786    Returns:
5787        The mapped expression.
5788    """
5789
5790    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5791        if isinstance(node, Placeholder):
5792            if node.name:
5793                new_name = kwargs.get(node.name)
5794                if new_name:
5795                    return convert(new_name)
5796            else:
5797                try:
5798                    return convert(next(args))
5799                except StopIteration:
5800                    pass
5801        return node
5802
5803    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression: expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5806def expand(
5807    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5808) -> Expression:
5809    """Transforms an expression by expanding all referenced sources into subqueries.
5810
5811    Examples:
5812        >>> from sqlglot import parse_one
5813        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5814        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5815
5816        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5817        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5818
5819    Args:
5820        expression: The expression to expand.
5821        sources: A dictionary of name to Subqueryables.
5822        copy: Whether or not to copy the expression during transformation. Defaults to True.
5823
5824    Returns:
5825        The transformed expression.
5826    """
5827
5828    def _expand(node: Expression):
5829        if isinstance(node, Table):
5830            name = table_name(node)
5831            source = sources.get(name)
5832            if source:
5833                subquery = source.subquery(node.alias or name)
5834                subquery.comments = [f"source: {name}"]
5835                return subquery.transform(_expand, copy=False)
5836        return node
5837
5838    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5841def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5842    """
5843    Returns a Func expression.
5844
5845    Examples:
5846        >>> func("abs", 5).sql()
5847        'ABS(5)'
5848
5849        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5850        'CAST(5 AS DOUBLE)'
5851
5852    Args:
5853        name: the name of the function to build.
5854        args: the args used to instantiate the function of interest.
5855        dialect: the source dialect.
5856        kwargs: the kwargs used to instantiate the function of interest.
5857
5858    Note:
5859        The arguments `args` and `kwargs` are mutually exclusive.
5860
5861    Returns:
5862        An instance of the function of interest, or an anonymous function, if `name` doesn't
5863        correspond to an existing `sqlglot.expressions.Func` class.
5864    """
5865    if args and kwargs:
5866        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5867
5868    from sqlglot.dialects.dialect import Dialect
5869
5870    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5871    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5872
5873    parser = Dialect.get_or_raise(dialect)().parser()
5874    from_args_list = parser.FUNCTIONS.get(name.upper())
5875
5876    if from_args_list:
5877        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5878    else:
5879        kwargs = kwargs or {"expressions": converted}
5880        function = Anonymous(this=name, **kwargs)
5881
5882    for error_message in function.error_messages(converted):
5883        raise ValueError(error_message)
5884
5885    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true() -> sqlglot.expressions.Boolean:
5888def true() -> Boolean:
5889    """
5890    Returns a true Boolean expression.
5891    """
5892    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5895def false() -> Boolean:
5896    """
5897    Returns a false Boolean expression.
5898    """
5899    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5902def null() -> Null:
5903    """
5904    Returns a Null expression.
5905    """
5906    return Null()

Returns a Null expression.

TRUE = (BOOLEAN this: True)
FALSE = (BOOLEAN this: False)
NULL = (NULL )